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.

refactor(actions): isolate the actions backend behind a facade (#128984)

Thomas Obermüller9e690f001f29
diff --git a/ee/api/test/test_action.py b/ee/api/test/test_action.py
index c9cd8bb11450..cd25b068d9f5 100644
--- a/ee/api/test/test_action.py
+++ b/ee/api/test/test_action.py
@@ -7,9 +7,10 @@ from posthog.test.base import APIBaseTest
from rest_framework import status
from posthog.cloud_utils import is_cloud
-from posthog.models import Tag
+from posthog.models import Tag, TaggedItem
+from posthog.models.tagged_item_registry import content_type_id_for_legacy_field
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
# Testing enterprise properties of actions here (i.e., tagging).
@@ -76,9 +77,10 @@ class TestActionApi(APIBaseTest):
assert not is_cloud()
tag = Tag.objects.create(name="tag", team=self.team)
+ action_content_type_id = content_type_id_for_legacy_field("action")
for i in range(20):
- action = Action.objects.create(team=self.team, name=f"action_{i}")
- action.tagged_items.create(tag=tag)
+ action = create_action(team=self.team, name=f"action_{i}")
+ TaggedItem.objects.create(tag=tag, content_type_id=action_content_type_id, object_id=action.id)
# base request queries + the single bulk access-control preload (one query covering all
# actions, replacing the previous per-action access-control lookups)
diff --git a/ee/clickhouse/models/test/test_action.py b/ee/clickhouse/models/test/test_action.py
index cb9e7f2a6c1e..706c2090b1a6 100644
--- a/ee/clickhouse/models/test/test_action.py
+++ b/ee/clickhouse/models/test/test_action.py
@@ -3,7 +3,7 @@ from posthog.test.base import BaseTest
from posthog.hogql.compiler.bytecode import create_bytecode
from posthog.hogql.property import action_to_expr
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, get_action_bytecode
from common.hogvm.python.operation import (
HOGQL_BYTECODE_IDENTIFIER as _H,
@@ -14,7 +14,7 @@ from common.hogvm.python.operation import (
class TestActionBytecode(BaseTest):
def test_bytecode_for_hogql_step_property(self):
- action1 = Action.objects.create(
+ action1 = create_action(
team=self.team,
name="action1",
steps_json=[
@@ -25,9 +25,10 @@ class TestActionBytecode(BaseTest):
],
)
- self.assertEqual(action1.bytecode, create_bytecode(action_to_expr(action1)).bytecode)
+ bytecode = get_action_bytecode(action1).bytecode
+ self.assertEqual(bytecode, create_bytecode(action_to_expr(action1)).bytecode)
self.assertEqual(
- action1.bytecode,
+ bytecode,
[
_H,
HOGQL_BYTECODE_VERSION,
diff --git a/ee/clickhouse/models/test/test_cohort.py b/ee/clickhouse/models/test/test_cohort.py
index 2c77e2d82351..40bb59458ce8 100644
--- a/ee/clickhouse/models/test/test_cohort.py
+++ b/ee/clickhouse/models/test/test_cohort.py
@@ -23,7 +23,7 @@ from posthog.clickhouse.client import sync_execute
from posthog.models.team import Team
from posthog.test.persons import create_person, delete_person, update_person
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_ID, GET_STATIC_COHORTPEOPLE_BY_COHORT_ID
@@ -218,13 +218,13 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
timestamp=datetime.now() - timedelta(hours=12),
)
- cohort1 = Cohort.objects.create(team=self.team, groups=[{"action_id": action.pk, "days": 1}], name="cohort1")
+ cohort1 = Cohort.objects.create(team=self.team, groups=[{"action_id": action.id, "days": 1}], name="cohort1")
self.calculate_cohort_hogql_test_harness(cohort1, 0)
results = self._get_cohortpeople(cohort1)
self.assertEqual(len(results), 2)
- cohort2 = Cohort.objects.create(team=self.team, groups=[{"action_id": action.pk, "days": 1}], name="cohort2")
+ cohort2 = Cohort.objects.create(team=self.team, groups=[{"action_id": action.id, "days": 1}], name="cohort2")
self.calculate_cohort_hogql_test_harness(cohort2, 0)
results = self._get_cohortpeople(cohort2)
@@ -308,7 +308,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
# test operators
cohort1 = Cohort.objects.create(
team=self.team,
- groups=[{"action_id": action.pk, "days": 3, "count": 2, "count_operator": "gte"}],
+ groups=[{"action_id": action.id, "days": 3, "count": 2, "count_operator": "gte"}],
name="cohort1",
)
self.calculate_cohort_hogql_test_harness(cohort1, 0)
@@ -318,7 +318,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
cohort2 = Cohort.objects.create(
team=self.team,
- groups=[{"action_id": action.pk, "days": 3, "count": 1, "count_operator": "lte"}],
+ groups=[{"action_id": action.id, "days": 3, "count": 1, "count_operator": "lte"}],
name="cohort2",
)
self.calculate_cohort_hogql_test_harness(cohort2, 0)
@@ -328,7 +328,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
cohort3 = Cohort.objects.create(
team=self.team,
- groups=[{"action_id": action.pk, "days": 3, "count": 1, "count_operator": "eq"}],
+ groups=[{"action_id": action.id, "days": 3, "count": 1, "count_operator": "eq"}],
name="cohort3",
)
self.calculate_cohort_hogql_test_harness(cohort3, 0)
@@ -671,7 +671,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
self.assertFalse(Cohort.objects.get().is_calculating)
def test_query_with_multiple_new_style_cohorts(self):
- action1 = Action.objects.create(
+ action1 = create_action(
team=self.team,
name="action1",
steps_json=[
@@ -746,7 +746,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
"type": "AND",
"values": [
{
- "key": action1.pk,
+ "key": action1.id,
"event_type": "actions",
"time_value": 2,
"time_interval": "week",
@@ -935,7 +935,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
def test_cohortpeople_action_all_events(self):
# Create an action that matches all events (no specific event defined)
- action = Action.objects.create(team=self.team, name="all events", steps_json=[{"event": None}])
+ action = create_action(team=self.team, name="all events", steps_json=[{"event": None}])
# Create two people
create_person(
@@ -969,7 +969,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):
# Create a cohort based on the "all events" action
cohort = Cohort.objects.create(
- team=self.team, groups=[{"action_id": action.pk, "days": 1}], name="cohort_all_events"
+ team=self.team, groups=[{"action_id": action.id, "days": 1}], name="cohort_all_events"
)
cohort.calculate_people_ch(pending_version=0)
diff --git a/ee/clickhouse/queries/test/test_cohort_query.py b/ee/clickhouse/queries/test/test_cohort_query.py
index ad64ed4f4d9e..c5a997147abd 100644
--- a/ee/clickhouse/queries/test/test_cohort_query.py
+++ b/ee/clickhouse/queries/test/test_cohort_query.py
@@ -24,7 +24,7 @@ from posthog.models import Team
from posthog.models.property import PropertyGroup
from posthog.models.property.parse import expand_cohort_properties, parse_property_group_data
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
@@ -81,7 +81,7 @@ def _properties(properties: dict[str, Any], team: Optional[Team] = None) -> Prop
class TestCohortQuery(ClickhouseTestMixin, BaseTest):
def test_basic_query(self):
- action1 = Action.objects.create(
+ action1 = create_action(
team=self.team,
name="action1",
steps_json=[
@@ -185,7 +185,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
"type": "AND",
"values": [
{
- "key": action1.pk,
+ "key": action1.id,
"event_type": "actions",
"time_value": 2,
"time_interval": "week",
@@ -1326,7 +1326,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
assert sorted([p1.uuid, p2.uuid, p3.uuid]) == sorted([r[0] for r in res])
def test_person_properties_with_pushdowns(self):
- action1 = Action.objects.create(
+ action1 = create_action(
team=self.team,
name="action1",
steps_json=[
@@ -1429,7 +1429,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
"type": "AND",
"values": [
{
- "key": action1.pk,
+ "key": action1.id,
"event_type": "actions",
"time_value": 2,
"time_interval": "week",
@@ -2367,7 +2367,7 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
properties={"name": "test", "email": "[email protected]"},
)
- action1 = Action.objects.create(
+ action1 = create_action(
team=self.team,
name="action1",
steps_json=[
@@ -2407,13 +2407,13 @@ class TestCohortQuery(ClickhouseTestMixin, BaseTest):
"type": "AND",
"values": [
{
- "key": action1.pk,
+ "key": action1.id,
"event_type": "actions",
"time_interval": "day",
"time_value": 7,
"seq_time_interval": "day",
"seq_time_value": 3,
- "seq_event": action1.pk,
+ "seq_event": action1.id,
"seq_event_type": "actions",
"value": "performed_event_sequence",
"type": "behavioral",
@@ -3438,7 +3438,7 @@ class TestCohortNegationValidation(BaseTest):
other_team = Team.objects.create(organization=self.organization, project=self.project)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="action",
steps_json=[
@@ -3468,7 +3468,7 @@ class TestCohortNegationValidation(BaseTest):
"type": "OR",
"values": [
{
- "key": action.pk,
+ "key": action.id,
"type": "behavioral",
"value": "performed_event",
"negation": False,
diff --git a/ee/clickhouse/views/test/test_experiment_saved_metrics.py b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
index 2feb8aaa2644..c44f2223437a 100644
--- a/ee/clickhouse/views/test/test_experiment_saved_metrics.py
+++ b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
@@ -6,7 +6,7 @@ from rest_framework import status
from posthog.constants import AvailableFeature
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.experiments.backend.experiment_saved_metric_service import ExperimentSavedMetricService
from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -926,10 +926,8 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
def test_saved_metric_refreshes_action_names(self):
"""Test that saved metrics show current action names when actions are renamed."""
- from products.actions.backend.models.action import Action
-
# Create an action
- action = Action.objects.create(team=self.team, name="Original Action Name")
+ action = create_action(team=self.team, name="Original Action Name")
# Create a saved metric using the action
response = self.client.post(
@@ -952,8 +950,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
saved_metric_id = response.json()["id"]
# Rename the action
- action.name = "Renamed Action"
- action.save()
+ update_action(action, name="Renamed Action")
# Fetch the saved metric
response = self.client.get(f"/api/projects/{self.team.id}/experiment_saved_metrics/{saved_metric_id}/")
@@ -965,10 +962,8 @@ 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 products.actions.backend.models.action import Action
-
# Create an action
- action = Action.objects.create(team=self.team, name="Action to Delete")
+ action = create_action(team=self.team, name="Action to Delete")
action_id = action.id
# Create a saved metric using the action
@@ -992,8 +987,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
saved_metric_id = response.json()["id"]
# Delete the action
- action.deleted = True
- action.save()
+ update_action(action, deleted=True)
# Fetch the saved metric
response = self.client.get(f"/api/projects/{self.team.id}/experiment_saved_metrics/{saved_metric_id}/")
@@ -1064,7 +1058,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
def _seed_metrics_for_event_filter(self) -> None:
# Created via the ORM so the stored query JSON is exactly what the filter inspects. The action fires
# on the "signup" event, so its metric is discoverable by that event — not by the action's label.
- signup_action = Action.objects.create(team=self.team, name="Completed signup", steps_json=[{"event": "signup"}])
+ signup_action = create_action(team=self.team, name="Completed signup", steps_json=[{"event": "signup"}])
for name, source in [
("Pageview mean", {"kind": "EventsNode", "event": "$pageview"}),
("Purchase mean", {"kind": "EventsNode", "event": "purchase"}),
diff --git a/ee/clickhouse/views/test/test_experiments_action_names.py b/ee/clickhouse/views/test/test_experiments_action_names.py
index 4385c7eeb1e6..605577b58935 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 products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, update_action
from ee.api.test.base import APILicensedTest
@@ -15,7 +15,7 @@ class TestExperimentActionNameRefresh(APILicensedTest):
)
def test_inline_metric_refreshes_action_names(self, _name, metrics_field):
# Create an action
- action = Action.objects.create(team=self.team, name="Original Action Name")
+ action = create_action(team=self.team, name="Original Action Name")
# Create an experiment with an inline metric using the action
response = self.client.post(
@@ -53,8 +53,7 @@ class TestExperimentActionNameRefresh(APILicensedTest):
experiment_id = response.json()["id"]
# Rename the action
- action.name = "Renamed Action"
- action.save()
+ update_action(action, name="Renamed Action")
# Fetch the experiment
response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_id}/")
@@ -75,7 +74,7 @@ class TestExperimentActionNameRefresh(APILicensedTest):
)
def test_inline_metric_with_different_id_types(self, _name, id_type):
# Create an action
- action = Action.objects.create(team=self.team, name="Action Name")
+ action = create_action(team=self.team, name="Action Name")
# Create an experiment with an inline metric using the action
response = self.client.post(
@@ -113,8 +112,7 @@ class TestExperimentActionNameRefresh(APILicensedTest):
experiment_id = response.json()["id"]
# Rename the action
- action.name = "Action Name Renamed"
- action.save()
+ update_action(action, name="Action Name Renamed")
# Fetch the experiment
response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_id}/")
@@ -127,7 +125,7 @@ class TestExperimentActionNameRefresh(APILicensedTest):
def test_inline_metric_preserves_name_for_deleted_action(self):
# Create an action
- action = Action.objects.create(team=self.team, name="Action to Delete")
+ action = create_action(team=self.team, name="Action to Delete")
action_id = action.id
# Create an experiment with an inline metric using the action
@@ -166,8 +164,7 @@ class TestExperimentActionNameRefresh(APILicensedTest):
experiment_id = response.json()["id"]
# Delete the action
- action.deleted = True
- action.save()
+ update_action(action, deleted=True)
# Fetch the experiment
response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_id}/")
@@ -188,8 +185,8 @@ class TestExperimentActionNameRefresh(APILicensedTest):
)
def test_funnel_metric_refreshes_action_names(self, _name, metrics_field):
# Create two actions for funnel steps
- action1 = Action.objects.create(team=self.team, name="Funnel Step 1 Original")
- action2 = Action.objects.create(team=self.team, name="Funnel Step 2 Original")
+ action1 = create_action(team=self.team, name="Funnel Step 1 Original")
+ action2 = create_action(team=self.team, name="Funnel Step 2 Original")
# Create an experiment with a funnel metric using actions
response = self.client.post(
@@ -234,10 +231,8 @@ class TestExperimentActionNameRefresh(APILicensedTest):
experiment_id = response.json()["id"]
# Rename both actions
- action1.name = "Funnel Step 1 Renamed"
- action1.save()
- action2.name = "Funnel Step 2 Renamed"
- action2.save()
+ update_action(action1, name="Funnel Step 1 Renamed")
+ update_action(action2, name="Funnel Step 2 Renamed")
# Fetch the experiment
response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_id}/")
@@ -258,8 +253,8 @@ class TestExperimentActionNameRefresh(APILicensedTest):
)
def test_ratio_metric_refreshes_action_names(self, _name, metrics_field):
# Create two actions for numerator and denominator
- numerator_action = Action.objects.create(team=self.team, name="Numerator Original")
- denominator_action = Action.objects.create(team=self.team, name="Denominator Original")
+ numerator_action = create_action(team=self.team, name="Numerator Original")
+ denominator_action = create_action(team=self.team, name="Denominator Original")
# Create an experiment with a ratio metric using actions
response = self.client.post(
@@ -302,10 +297,8 @@ class TestExperimentActionNameRefresh(APILicensedTest):
experiment_id = response.json()["id"]
# Rename both actions
- numerator_action.name = "Numerator Renamed"
- numerator_action.save()
- denominator_action.name = "Denominator Renamed"
- denominator_action.save()
+ update_action(numerator_action, name="Numerator Renamed")
+ update_action(denominator_action, name="Denominator Renamed")
# Fetch the experiment
response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment_id}/")
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 9d4a81a33612..712b8c386b1f 100644
--- a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
@@ -21,7 +21,7 @@ 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.actions.backend.facade.testing import create_action, delete_action
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
from ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkit, final_answer
@@ -35,7 +35,7 @@ class DummyToolkit(TaxonomyAgentToolkit):
class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
- self.action = Action.objects.create(team=self.team, name="action1", steps_json=[{"event": "event1"}])
+ self.action = create_action(team=self.team, name="action1", steps_json=[{"event": "event1"}])
def _create_taxonomy(self):
PropertyDefinition.objects.create(
@@ -616,7 +616,7 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):
)
def test_retrieve_event_or_action_properties_when_no_actions_exist_and_action_id_incorrect(self):
- Action.objects.all().delete()
+ delete_action(self.action)
toolkit = DummyToolkit(self.team, self.user)
incorrect_action_id = 9999
diff --git a/ee/hogai/chat_agent/query_planner/toolkit.py b/ee/hogai/chat_agent/query_planner/toolkit.py
index 7731c3659afc..ef640d65fccb 100644
--- a/ee/hogai/chat_agent/query_planner/toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/toolkit.py
@@ -24,7 +24,8 @@ from posthog.settings import EE_AVAILABLE
from posthog.taxonomy.property_access import restricted_property_names
from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, CoreFilterDefinition
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import list_actions
+from products.actions.backend.facade.contracts import ActionNotFound
from products.event_definitions.backend.models.property_definition import (
PropertyDefinition,
PropertyType,
@@ -343,8 +344,8 @@ class TaxonomyAgentToolkit:
"""
try:
response, verbose_name = self._retrieve_event_or_action_taxonomy(event_name_or_action_id)
- except Action.DoesNotExist:
- project_actions = Action.objects.filter(team__project_id=self._team.project_id, deleted=False)
+ except ActionNotFound:
+ project_actions = list_actions(project_id=self._team.project_id)
if not project_actions:
return "No actions exist in the project."
return f"Action {event_name_or_action_id} does not exist in the taxonomy. Verify that the action ID is correct and try again."
diff --git a/ee/hogai/chat_agent/rag/nodes.py b/ee/hogai/chat_agent/rag/nodes.py
index 5237dfcd93f2..b04d665a5bed 100644
--- a/ee/hogai/chat_agent/rag/nodes.py
+++ b/ee/hogai/chat_agent/rag/nodes.py
@@ -21,7 +21,7 @@ from posthog.hogql_queries.ai.vector_search_query_runner import (
)
from posthog.hogql_queries.query_runner import ExecutionMode
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_actions
from ee.hogai.core.node import AssistantNode
from ee.hogai.utils.embeddings import embed_search_query, get_azure_embeddings_client
@@ -115,7 +115,7 @@ class InsightRagContextNode(AssistantNode):
"""Search for action IDs using vector search and UI context, reports metrics."""
start_time = time.time()
try:
- # action.id in UI context actions is typed as float from schema.py, so we need to convert it to int to match the Action.id field
+ # action.id in UI context actions is typed as float from schema.py, so we need to convert it to int to match the action id
actions_in_context = context["actions_in_context"]
embedding = context["embedding"]
ids = [str(int(action.id)) for action in actions_in_context] if actions_in_context else []
@@ -155,9 +155,7 @@ class InsightRagContextNode(AssistantNode):
if len(ids) == 0:
return ""
- actions = Action.objects.filter(team__project_id=self._team.project_id, id__in=ids).only(
- "id", "name", "description"
- )
+ actions = get_actions(project_id=self._team.project_id, action_ids=[int(action_id) for action_id in ids])
root = ET.Element("defined_actions")
for action in actions:
diff --git a/ee/hogai/chat_agent/rag/test/test_nodes.py b/ee/hogai/chat_agent/rag/test/test_nodes.py
index 500b70d62cbd..80694924bfe4 100644
--- a/ee/hogai/chat_agent/rag/test/test_nodes.py
+++ b/ee/hogai/chat_agent/rag/test/test_nodes.py
@@ -12,7 +12,7 @@ from posthog.schema import MaxActionContext, MaxUIContext, TeamTaxonomyQuery
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models.ai.utils import PgEmbeddingRow, bulk_create_pg_embeddings
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from ee.hogai.chat_agent.rag.nodes import InsightRagContextNode
from ee.hogai.utils.types import AssistantState
@@ -36,7 +36,7 @@ from ee.hogai.utils.types import AssistantState
class TestInsightRagContextNode(ClickhouseTestMixin, BaseTest):
def setUp(self):
super().setUp()
- self.action = Action.objects.create(
+ self.action = create_action(
team=self.team,
name="Action",
description="Description",
@@ -85,7 +85,7 @@ class TestInsightRagContextNode(ClickhouseTestMixin, BaseTest):
@patch.object(InsightRagContextNode, "context_manager", new_callable=lambda: MagicMock())
def test_injects_actions_from_context(self, mock_context_manager, cohere_mock, embed_mock):
# Create a second action that will come from UI context
- context_action = Action.objects.create(
+ context_action = create_action(
team=self.team,
name="Context Action",
description="From UI Context",
@@ -117,7 +117,7 @@ class TestInsightRagContextNode(ClickhouseTestMixin, BaseTest):
# Make embedding fail
embed_mock.side_effect = ValueError("Embedding failed")
- context_action = Action.objects.create(
+ context_action = create_action(
team=self.team,
name="Context Only Action",
description="Only from context",
diff --git a/ee/hogai/chat_agent/retention/test/test_nodes.py b/ee/hogai/chat_agent/retention/test/test_nodes.py
index 4f919f4c9a40..18fbd80ce77b 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 products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.posthog_ai.backend.models.assistant import Conversation
from ee.hogai.chat_agent.retention.nodes import RetentionGeneratorNode, RetentionSchemaGeneratorOutput
@@ -26,7 +26,7 @@ class TestRetentionGeneratorNode(BaseTest):
def setUp(self):
super().setUp()
- self.action = Action.objects.create(team=self.team, name="Test Action")
+ self.action = create_action(team=self.team, name="Test Action")
self.schema = AssistantRetentionQuery(
retentionFilter=AssistantRetentionFilter(
targetEntity=AssistantRetentionEventsNode(id="targetEntity"),
diff --git a/ee/hogai/chat_agent/taxonomy/test/test_events.py b/ee/hogai/chat_agent/taxonomy/test/test_events.py
index 9cbfa8cc845f..aa7ac182ca29 100644
--- a/ee/hogai/chat_agent/taxonomy/test/test_events.py
+++ b/ee/hogai/chat_agent/taxonomy/test/test_events.py
@@ -8,7 +8,7 @@ from posthog.schema import CachedEventTaxonomyQueryResponse
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.actions.backend.facade.testing import create_action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from ee.hogai.chat_agent.taxonomy.toolkit import TaxonomyAgentToolkit
@@ -81,7 +81,7 @@ class TestEvents(ClickhouseTestMixin, NonAtomicBaseTest):
properties={},
)
- Action.objects.create(
+ create_action(
id=232, team=self.team, name="action1", description="Test Description", steps_json=[{"event": "event1"}]
)
diff --git a/ee/hogai/chat_agent/taxonomy/toolkit.py b/ee/hogai/chat_agent/taxonomy/toolkit.py
index 5c9c0849240d..f9e20bb53e36 100644
--- a/ee/hogai/chat_agent/taxonomy/toolkit.py
+++ b/ee/hogai/chat_agent/taxonomy/toolkit.py
@@ -34,7 +34,8 @@ from posthog.sync import database_sync_to_async
from posthog.taxonomy.property_access import restricted_property_names
from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, CoreFilterDefinition
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import list_actions
+from products.actions.backend.facade.contracts import Action, ActionNotFound
from products.event_definitions.backend.models.property_definition import (
PropertyDefinition,
PropertyType,
@@ -509,7 +510,7 @@ class TaxonomyAgentToolkit:
event_name_or_action_id = task.args["event_name_or_action_id"]
try:
response, verbose_name = await self._retrieve_event_or_action_taxonomy(event_name_or_action_id)
- except Action.DoesNotExist:
+ except ActionNotFound:
project_actions = await self._get_project_actions()
if not project_actions:
result = TaxonomyErrorMessages.no_actions_exist()
@@ -770,7 +771,7 @@ class TaxonomyAgentToolkit:
@database_sync_to_async(thread_sensitive=False)
def _get_project_actions(self) -> list[Action]:
- return list(Action.objects.filter(team__project_id=self._team.project_id, deleted=False))
+ return list_actions(project_id=self._team.project_id)
async def retrieve_event_or_action_properties_parallel(
self, event_name_or_action_ids: list[str | int]
diff --git a/ee/hogai/chat_agent/test/test_chat_agent.py b/ee/hogai/chat_agent/test/test_chat_agent.py
index 88b368127616..e1bb09f7c826 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 products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import acreate_action
from products.posthog_ai.backend.models.assistant import Conversation, CoreMemory
from ee.hogai.chat_agent.funnels.nodes import FunnelsSchemaGeneratorOutput
@@ -545,7 +545,7 @@ class TestChatAgent(ClickhouseTestMixin, BaseAssistantTest):
"ee.hogai.chat_agent.memory.nodes.MemoryCollectorNode._model", return_value=messages.AIMessage(content="[Done]")
)
async def test_full_retention_flow(self, memory_collector_mock, root_mock, generator_mock, title_generator_mock):
- action = await Action.objects.acreate(team=self.team, name="Marius Tech Tips")
+ action = await acreate_action(team=self.team, name="Marius Tech Tips")
res1 = FakeAnthropicRunnableLambdaWithTokenCounter(
lambda _: messages.AIMessage(
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.py
index 2a5a78364c22..2ae768963805 100644
--- a/ee/hogai/context/entity_search/context.py
+++ b/ee/hogai/context/entity_search/context.py
@@ -15,13 +15,14 @@ from posthog.api.search import (
FEATURE_FLAG_SEARCH_CONFIG,
LIMIT as SEARCH_LIMIT,
EntityConfig,
+ FacadeSearch,
search_entities as search_entities_fts,
+ search_live_actions,
)
from posthog.models import Team, User
from posthog.sync import database_sync_to_async
from products.access_control.backend.facade.user_access_control import UserAccessControl
-from products.actions.backend.models.action import Action
from products.alerts.backend.models.alert import AlertConfiguration
from products.cohorts.backend.models.cohort import Cohort
from products.customer_analytics.backend.facade import api as customer_analytics_facade
@@ -93,12 +94,6 @@ ENTITY_MAP: dict[str, EntityConfig] = {
"filters": {"deleted": False},
},
"feature_flag": FEATURE_FLAG_SEARCH_CONFIG,
- "action": {
- "klass": Action,
- "search_fields": {"name": "A", "description": "C"},
- "extra_fields": ["name", "description"],
- "filters": {"deleted": False},
- },
"cohort": {
"klass": Cohort,
"search_fields": {"name": "A", "description": "C", "filters": "B"},
@@ -130,6 +125,18 @@ Map of entity names to their class, search_fields and extra_fields.
The value in search_fields corresponds to the PostgreSQL weighting i.e. A, B, C or D.
"""
+
+# Actions are searched through the actions facade rather than unioned by model class, so they are not in ENTITY_MAP.
+ACTION_ENTITY = "action"
+FACADE_SEARCHES: dict[str, FacadeSearch] = {ACTION_ENTITY: search_live_actions}
+_UNION_ENTITY_NAMES = [*ENTITY_MAP]
+# Actions keep their place between feature flags and cohorts in the counts.
+COUNTED_ENTITIES = [
+ *_UNION_ENTITY_NAMES[: _UNION_ENTITY_NAMES.index("cohort")],
+ ACTION_ENTITY,
+ *_UNION_ENTITY_NAMES[_UNION_ENTITY_NAMES.index("cohort") :],
+]
+
EXCLUDE_FROM_DISPLAY: dict[str, set[str]] = {
"insight": {"query", "query_metadata"},
"notebook": {"title"},
@@ -172,7 +179,7 @@ class EntitySearchContext:
Tuple of (results list, counts dict)
"""
if entity_types == "all":
- entity_types = {*ENTITY_MAP, "hog_flow"}
+ entity_types = {*ENTITY_MAP, ACTION_ENTITY, "hog_flow"}
results: list[dict] = []
counts: dict[str, int | None] = {}
@@ -204,6 +211,8 @@ class EntitySearchContext:
self._team.project_id,
self, # type: ignore
ENTITY_MAP,
+ facade_searches=FACADE_SEARCHES,
+ counted_entities=COUNTED_ENTITIES,
)
assert fts_counts is not None
counts.update(fts_counts)
@@ -294,6 +303,8 @@ class EntitySearchContext:
entity_map=ENTITY_MAP,
limit=limit,
offset=offset,
+ facade_searches=FACADE_SEARCHES,
+ counted_entities=COUNTED_ENTITIES,
)
all_entities.extend(db_results)
assert maybe_count is not None
diff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.py
index 0cb8e8baa57e..d39bd967cd29 100644
--- a/ee/hogai/context/entity_search/test/test_context.py
+++ b/ee/hogai/context/entity_search/test/test_context.py
@@ -16,7 +16,7 @@ from posthog.constants import AvailableFeature
from posthog.models import Team
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import acreate_action
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
@@ -282,8 +282,8 @@ class TestEntitySearchContext(NonAtomicBaseTest):
assert "archived_flag" not in result_keys
async def test_action_filters_exclude_deleted(self):
- await Action.objects.acreate(team=self.team, name="active action", deleted=False, created_by=self.user)
- await Action.objects.acreate(team=self.team, name="deleted action", deleted=True, created_by=self.user)
+ await acreate_action(team=self.team, name="active action", deleted=False, created_by=self.user)
+ await acreate_action(team=self.team, name="deleted action", deleted=True, created_by=self.user)
results, _ = await self.context.search_entities({"action"}, "action")
@@ -325,7 +325,7 @@ class TestEntitySearchContext(NonAtomicBaseTest):
team=self.team, name="deleted insight", deleted=True, saved=True, created_by=self.user
)
await Dashboard.objects.acreate(team=self.team, name="deleted dashboard", deleted=True, created_by=self.user)
- await Action.objects.acreate(team=self.team, name="deleted action", deleted=True, created_by=self.user)
+ await acreate_action(team=self.team, name="deleted action", deleted=True, created_by=self.user)
await Cohort.objects.acreate(team=self.team, name="deleted cohort", deleted=True, created_by=self.user)
await Survey.objects.acreate(
team=self.team,
diff --git a/ee/hogai/core/mixins.py b/ee/hogai/core/mixins.py
index 4e50610cd7e3..ae168fca0a04 100644
--- a/ee/hogai/core/mixins.py
+++ b/ee/hogai/core/mixins.py
@@ -14,7 +14,8 @@ from posthog.event_usage import groups
from posthog.models import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
from products.posthog_ai.backend.models.assistant import Conversation, CoreMemory
from ee.hogai.utils.dispatcher import AssistantDispatcher, create_dispatcher_from_config
@@ -202,8 +203,8 @@ class TaxonomyUpdateDispatcherNodeMixin:
)
case "retrieve_action_properties" | "retrieve_action_property_values":
try:
- action_model = Action.objects.get(
- pk=action.tool_input["action_id"], team__project_id=self._team.project_id
+ action_model = get_action(
+ action_id=int(action.tool_input["action_id"]), project_id=self._team.project_id
)
if action.tool == "retrieve_action_properties":
substeps.append(f"Exploring `{action_model.name}` action properties")
@@ -211,7 +212,7 @@ class TaxonomyUpdateDispatcherNodeMixin:
substeps.append(
f"Analyzing `{action.tool_input['property_name']}` action property of `{action_model.name}`"
)
- except Action.DoesNotExist:
+ except ActionNotFound:
pass
content = "Picking relevant events and properties"
diff --git a/ee/hogai/summarizers/actions.py b/ee/hogai/summarizers/actions.py
index f862fc2b6553..5e437cc426d4 100644
--- a/ee/hogai/summarizers/actions.py
+++ b/ee/hogai/summarizers/actions.py
@@ -1,6 +1,6 @@
from collections import defaultdict
-from products.actions.backend.models.action import Action, ActionStepJSON, ActionStepMatching
+from products.actions.backend.facade.contracts import Action, ActionStep, ActionStepMatching
from .property_filters import (
PropertyFilterCollectionDescriber,
@@ -51,7 +51,7 @@ class ActionSummarizer:
description = "\n\n".join(group_descriptions)
return description
- def _describe_action_step(self, step: ActionStepJSON, index: int) -> tuple[str, set[PropertyFilterTaxonomyEntry]]:
+ def _describe_action_step(self, step: ActionStep, index: int) -> tuple[str, set[PropertyFilterTaxonomyEntry]]:
taxonomy: set[PropertyFilterTaxonomyEntry] = set()
description: list[str] = []
diff --git a/ee/hogai/summarizers/chains.py b/ee/hogai/summarizers/chains.py
index 8e5a047634d6..9506c6f499b0 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 products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts 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 09769479804d..31bf389fb5e7 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 products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from ee.hogai.summarizers.actions import ActionSummarizer
@@ -13,7 +13,7 @@ class TestActionSummarizer(BaseTest):
json_steps = """
[{"event":"$pageview","properties":[{"key":"$browser","type":"event","value":["Chrome"],"operator":"exact"},{"key":"$geoip_country_name","type":"person","value":["United States"],"operator":"exact"}],"selector":null,"tag_name":null,"text":null,"text_matching":null,"href":null,"href_matching":"contains","url":"/max","url_matching":"contains"},{"event":"$autocapture","properties":[{"key":"tag_name","type":"element","value":["button"],"operator":"exact"}],"selector":"button","tag_name":null,"text":"Send","text_matching":"contains","href":"/max","href_matching":"exact","url":"\\/max","url_matching":"regex"},{"event":"chat with ai","properties":null,"selector":null,"tag_name":null,"text":null,"text_matching":null,"href":null,"href_matching":"contains","url":null,"url_matching":null}]
"""
- action = Action.objects.create(
+ action = create_action(
name="Test Action", description="Test Description", steps_json=json.loads(json_steps), team=self.team
)
summarizer = ActionSummarizer(action)
@@ -38,9 +38,7 @@ class TestActionSummarizer(BaseTest):
{"event": "$pageview", "url": "/max"},
{"event": "$autocapture", "selector": "button", "text": "Send", "href": "/max", "url": "\\/max"},
]
- action = Action.objects.create(
- name="Test Action", description="Test Description", steps_json=steps, team=self.team
- )
+ action = create_action(name="Test Action", description="Test Description", steps_json=steps, team=self.team)
summarizer = ActionSummarizer(action)
expected_summary = r"""
Name: Test Action
diff --git a/ee/hogai/test/test_insights_assistant.py b/ee/hogai/test/test_insights_assistant.py
index f91f222f93f4..1df5329d73e4 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 products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import acreate_action
from products.posthog_ai.backend.models.assistant import Conversation
from ee.hogai.chat_agent.funnels.nodes import FunnelsSchemaGeneratorOutput
@@ -200,7 +200,7 @@ class TestChatAgent(BaseAssistantTest):
"ee.hogai.chat_agent.memory.nodes.MemoryCollectorNode._model", return_value=messages.AIMessage(content="[Done]")
)
async def test_insights_full_retention_flow(self, memory_collector_mock, root_mock, planner_mock, generator_mock):
- action = await Action.objects.acreate(team=self.team, name="Marius Tech Tips")
+ action = await acreate_action(team=self.team, name="Marius Tech Tips")
res1 = FakeAnthropicRunnableLambdaWithTokenCounter(
lambda _: messages.AIMessage(
diff --git a/ee/hogai/tools/full_text_search/test/test_tool.py b/ee/hogai/tools/full_text_search/test/test_tool.py
index 40c07d3c7732..b477adbcd6be 100644
--- a/ee/hogai/tools/full_text_search/test/test_tool.py
+++ b/ee/hogai/tools/full_text_search/test/test_tool.py
@@ -8,7 +8,7 @@ from django.apps import apps
from langchain_core.runnables import RunnableConfig
from ee.hogai.context import AssistantContextManager
-from ee.hogai.context.entity_search.context import ENTITY_MAP
+from ee.hogai.context.entity_search.context import ACTION_ENTITY, COUNTED_ENTITIES, ENTITY_MAP, FACADE_SEARCHES
from ee.hogai.core.shared_prompts import HYPERLINK_USAGE_INSTRUCTIONS
if TYPE_CHECKING:
@@ -46,7 +46,17 @@ class TestEntitySearchToolkit(NonAtomicBaseTest):
{"type": "action", "result_id": "101", "extra_fields": {"name": "Test Action"}, "rank": 0.80},
]
- def side_effect_func(entities, query, project_id, view, entity_map, limit=100, offset=0):
+ def side_effect_func(
+ entities,
+ query,
+ project_id,
+ view,
+ entity_map,
+ limit=100,
+ offset=0,
+ facade_searches=None,
+ counted_entities=None,
+ ):
return (all_results, dict.fromkeys(entities, 1), len(all_results))
mock_search_entities.side_effect = side_effect_func
@@ -54,7 +64,13 @@ class TestEntitySearchToolkit(NonAtomicBaseTest):
_ = await self.toolkit.execute(query="test query", search_kind=EntityKind.ALL)
mock_search_entities.assert_called_once_with(
- set(ENTITY_MAP.keys()), "test query", self.team.project_id, ANY, ENTITY_MAP
+ {*ENTITY_MAP.keys(), ACTION_ENTITY},
+ "test query",
+ self.team.project_id,
+ ANY,
+ ENTITY_MAP,
+ facade_searches=FACADE_SEARCHES,
+ counted_entities=COUNTED_ENTITIES,
)
@patch("ee.hogai.context.entity_search.context.search_entities_fts")
@@ -83,7 +99,17 @@ class TestEntitySearchToolkit(NonAtomicBaseTest):
},
]
- def side_effect_func(entities, query, project_id, view, entity_map, limit=100, offset=0):
+ def side_effect_func(
+ entities,
+ query,
+ project_id,
+ view,
+ entity_map,
+ limit=100,
+ offset=0,
+ facade_searches=None,
+ counted_entities=None,
+ ):
result = [result for result in all_results if result["type"] in entities]
return (result, {result["type"]: len(result) for result in result}, len(result))
diff --git a/posthog/api/search.py b/posthog/api/search.py
index f23eae527575..780054052ee4 100644
--- a/posthog/api/search.py
+++ b/posthog/api/search.py
@@ -1,8 +1,9 @@
import re
import operator
from collections import defaultdict
+from collections.abc import Mapping
from functools import reduce
-from typing import Any, Literal, TypedDict, cast
+from typing import Any, Literal, Protocol, TypedDict, cast
from django.db.models import BigIntegerField, CharField, F, Model, OuterRef, Q, QuerySet, Subquery, Value
from django.db.models.functions import Cast, JSONObject, Lower
@@ -19,7 +20,7 @@ from posthog.helpers.full_text_search import build_rank, process_query
from posthog.models import EventDefinition, PropertyDefinition
from products.access_control.backend.facade.user_access_control import UserAccessControl, model_to_resource
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import search_actions
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery, Node
@@ -103,11 +104,6 @@ ENTITY_MAP: dict[str, EntityConfig] = {
"search_fields": {"title": "A", "text_content": "C"},
"extra_fields": ["title", "content"],
},
- "action": {
- "klass": Action,
- "search_fields": {"name": "A", "description": "C"},
- "extra_fields": ["name", "description"],
- },
"cohort": {
"klass": Cohort,
"search_fields": {"name": "A", "description": "C"},
@@ -135,10 +131,51 @@ ENTITY_MAP: dict[str, EntityConfig] = {
},
}
-# Workflows are searched through the workflows facade rather than unioned by model class, so
-# they are not in ENTITY_MAP. `search_entities` merges them in when this entity is requested.
+
+class FacadeSearch(Protocol):
+ """A product facade's search, returning results in the shape of a union row, and the total."""
+
+ def __call__(
+ self,
+ *,
+ project_id: int,
+ query: str | None,
+ access_control: UserAccessControl,
+ limit: int,
+ with_access_levels: bool,
+ include_count: bool,
+ ) -> tuple[list[dict[str, Any]], int]: ...
+
+
+def _search_actions(**kwargs: Any) -> tuple[list[dict[str, Any]], int]:
+ return search_actions(include_deleted=True, **kwargs)
+
+
+def search_live_actions(**kwargs: Any) -> tuple[list[dict[str, Any]], int]:
+ """The action search for a caller that leaves soft-deleted actions out."""
+ return search_actions(include_deleted=False, **kwargs)
+
+
+def _search_workflows(**kwargs: Any) -> tuple[list[dict[str, Any]], int]:
+ results, count = search_workflows(include_archived=True, **kwargs)
+ for result in results:
+ result["extra_fields"].pop("status", None)
+ return results, count
+
+
+# Actions and workflows are searched through their products' facades rather than unioned by model
+# class, so they are not in ENTITY_MAP. `search_entities` merges them in when one is requested.
+ACTION_ENTITY = "action"
WORKFLOW_ENTITY = "hog_flow"
-SEARCHABLE_ENTITIES = [*ENTITY_MAP, WORKFLOW_ENTITY]
+FACADE_SEARCHES: dict[str, FacadeSearch] = {ACTION_ENTITY: _search_actions, WORKFLOW_ENTITY: _search_workflows}
+# Actions keep their place between notebooks and cohorts in the entity choices and the counts.
+_UNION_ENTITY_NAMES = [*ENTITY_MAP]
+_COUNTED_ENTITIES = [
+ *_UNION_ENTITY_NAMES[: _UNION_ENTITY_NAMES.index("cohort")],
+ ACTION_ENTITY,
+ *_UNION_ENTITY_NAMES[_UNION_ENTITY_NAMES.index("cohort") :],
+]
+SEARCHABLE_ENTITIES = [*_COUNTED_ENTITIES, WORKFLOW_ENTITY]
"""
Map of entity names to their class, search_fields and extra_fields.
@@ -191,6 +228,7 @@ class SearchViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
ENTITY_MAP,
include_counts=include_counts,
annotate_access_levels=self.user_access_control,
+ counted_entities=_COUNTED_ENTITIES,
)
response_data: dict[str, Any] = {"results": results}
@@ -210,12 +248,22 @@ def search_entities(
offset: int = 0,
include_counts: bool = True,
annotate_access_levels: UserAccessControl | None = None,
+ facade_searches: Mapping[str, FacadeSearch] = FACADE_SEARCHES,
+ counted_entities: list[str] | None = None,
) -> tuple[list[dict[str, Any]], dict[str, int | None] | None, int | None]:
- workflows_requested = WORKFLOW_ENTITY in entities
- entities = entities - {WORKFLOW_ENTITY}
+ """Search the requested entities: those in `entity_map` in one SQL union, those in `facade_searches`
+ through their products' facades, merged into one ranked page.
+
+ `counted_entities` names the keys `counts` starts with, in order, each None until searched. It
+ defaults to the `entity_map` keys.
+ """
+ requested_facades = [name for name in facade_searches if name in entities]
+ entities = entities - set(facade_searches)
# empty queryset to union things onto it
- counts: dict[str, int | None] = dict.fromkeys(entity_map) if include_counts else {}
+ counts: dict[str, int | None] = (
+ dict.fromkeys(counted_entities if counted_entities is not None else entity_map) if include_counts else {}
+ )
qs = (
Dashboard.objects.annotate(type=Value("empty", output_field=CharField()))
.filter(team__project_id=project_id)
@@ -243,41 +291,44 @@ def search_entities(
counts[entity_name] = klass_qs.count()
# order by rank. Ordering an empty union by a column no member added raises, which only
- # happens here when workflows were the one entity requested.
- if entities or not workflows_requested:
+ # happens here when facade-searched entities were the only ones requested.
+ if entities or not requested_facades:
if query:
qs = qs.order_by(F("rank").desc())
else:
qs = qs.order_by("type", F("_sort_name").asc(nulls_first=True))
- if not workflows_requested:
+ if not requested_facades:
# Get total count before pagination (only when needed)
total_count = qs.count() if include_counts else None
results = cast(list[dict[str, Any]], list(qs[offset : offset + limit]))
if annotate_access_levels is not None:
_annotate_user_access_levels(results, entity_map, annotate_access_levels)
else:
- workflow_results, workflow_count = search_workflows(
- project_id=project_id,
- query=query,
- access_control=view.user_access_control,
- limit=offset + limit,
- include_archived=True,
- with_access_levels=annotate_access_levels is not None,
- include_count=include_counts,
- )
- for result in workflow_results:
- result["extra_fields"].pop("status", None)
- if include_counts:
- counts[WORKFLOW_ENTITY] = workflow_count
+ facade_results: list[dict[str, Any]] = []
+ facade_count = 0
+ for name in requested_facades:
+ # Each source returns its first offset + limit rows, so the merged page is complete.
+ name_results, name_count = facade_searches[name](
+ project_id=project_id,
+ query=query,
+ access_control=view.user_access_control,
+ limit=offset + limit,
+ with_access_levels=annotate_access_levels is not None,
+ include_count=include_counts,
+ )
+ facade_results.extend(name_results)
+ facade_count += name_count
+ if include_counts:
+ counts[name] = name_count
union_results = cast(list[dict[str, Any]], list(qs[: offset + limit])) if entities else []
if annotate_access_levels is not None:
_annotate_user_access_levels(union_results, entity_map, annotate_access_levels)
- total_count = ((qs.count() if entities else 0) + workflow_count) if include_counts else None
+ total_count = ((qs.count() if entities else 0) + facade_count) if include_counts else None
- # Both inputs arrive in the database order, so a stable sort on the leading key keeps it.
- merged = [*union_results, *workflow_results]
+ # Every input arrives in the database order, so a stable sort on the leading key keeps it.
+ merged = [*union_results, *facade_results]
if query:
merged.sort(key=lambda result: result["rank"], reverse=True)
else:
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 34bd9bfcc962..19b49a66f903 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -55,7 +55,7 @@ from posthog.test.db_context_capturing import capture_db_queries
from posthog.test.persons import create_person
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillTrigger
from products.cohorts.backend.models.calculation_history import CohortCalculationHistory
from products.cohorts.backend.models.cohort import DEFAULT_COHORT_INSERT_BATCH_SIZE, Cohort, CohortType
@@ -409,7 +409,7 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin
distinct_id="person_1",
timestamp=datetime.now() - timedelta(hours=12),
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[
{
@@ -432,7 +432,7 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin
"type": "AND",
"values": [
{
- "key": action.pk,
+ "key": action.id,
"type": "behavioral",
"value": "performed_event",
"negation": False,
diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.py
index a385c1c366b7..83393602578b 100644
--- a/posthog/api/test/test_event.py
+++ b/posthog/api/test/test_event.py
@@ -31,7 +31,7 @@ from posthog.models.team.team_revenue_analytics_config import TeamRevenueAnalyti
from posthog.test.persons import create_person
from posthog.test.test_journeys import journeys_for
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
@@ -725,17 +725,17 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/events/?before=4d").json()
assert len(response["results"]) == 1
- action = Action.objects.create(team=self.team, steps_json=[{"event": "sign up"}])
+ action = create_action(team=self.team, steps_json=[{"event": "sign up"}])
response = self.client.get(
- f"/api/projects/{self.team.id}/events/?after=2020-01-09T00:00:00.000Z&action_id=%s" % action.pk
+ f"/api/projects/{self.team.id}/events/?after=2020-01-09T00:00:00.000Z&action_id=%s" % action.id
).json()
assert len(response["results"]) == 1
assert response["results"][0]["id"] == event1_uuid
response = self.client.get(
f"/api/projects/{self.team.id}/events/?after=2020-01-01T00:00:00.000Z&before=2020-01-09T00:00:00.000Z&action_id=%s"
- % action.pk
+ % action.id
).json()
assert len(response["results"]) == 1
assert response["results"][0]["id"] == event2_uuid
@@ -923,9 +923,9 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
assert response["results"][0]["timestamp"] == "2026-06-30T20:44:19.407000+00:00"
def test_action_no_steps(self):
- action = Action.objects.create(team=self.team)
+ action = create_action(team=self.team)
- response = self.client.get(f"/api/projects/{self.team.id}/events/?action_id=%s" % action.pk)
+ response = self.client.get(f"/api/projects/{self.team.id}/events/?action_id=%s" % action.id)
assert response.status_code == 200
assert len(response.json()["results"]) == 0
diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.py
index c6cb029b0ce1..3736ce226d46 100644
--- a/posthog/api/test/test_event_definition.py
+++ b/posthog/api/test/test_event_definition.py
@@ -26,7 +26,7 @@ from posthog.models import ActivityLog, EventDefinition, Organization, Tag, Team
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.taxonomy import definition_search
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
@time_machine.travel("2020-01-02", tick=False)
@@ -661,7 +661,7 @@ class TestEventDefinitionAPI(APIBaseTest):
assert whitespace_search_names == default_names
def test_event_type_event(self):
- action = Action.objects.create(team=self.demo_team, name="action1_app")
+ action = create_action(team=self.demo_team, name="action1_app")
response = self.client.get("/api/projects/@current/event_definitions/?search=app&event_type=event")
assert response.status_code == status.HTTP_200_OK
diff --git a/posthog/api/test/test_file_system.py b/posthog/api/test/test_file_system.py
index cc2fad1a640b..628ced4a4490 100644
--- a/posthog/api/test/test_file_system.py
+++ b/posthog/api/test/test_file_system.py
@@ -23,7 +23,8 @@ from posthog.models.file_system.file_system import FileSystem
from posthog.models.file_system.file_system_view_log import FileSystemViewLog
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.testing import create_action
from products.approvals.backend.models import ChangeRequest
from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
from products.cohorts.backend.models.cohort import Cohort
@@ -103,7 +104,7 @@ FILE_SYSTEM_ACTIVITY_CASES: list[tuple[str, FileSystemActivityCase]] = [
FileSystemActivityCase(
type_string="action",
scope="Action",
- create_instance=lambda test: Action.objects.create(
+ create_instance=lambda test: create_action(
team=test.team,
name="File system action",
created_by=test.user,
@@ -485,7 +486,8 @@ class TestLogApiFileSystemView(APIBaseTest):
def setUp(self) -> None:
super().setUp()
self.factory = APIRequestFactory()
- self.action = Action.objects.create(team=self.team, name="Action", created_by=self.user)
+ # Any file-system-synced model serves; a flag is one this suite can create directly.
+ self.viewed = FeatureFlag.objects.create(team=self.team, key="viewed-flag", created_by=self.user)
@parameterized.expand(
[
@@ -503,7 +505,7 @@ class TestLogApiFileSystemView(APIBaseTest):
if has_cookie:
request.COOKIES[settings.SESSION_COOKIE_NAME] = "session-key"
- log_api_file_system_view(request, self.action)
+ log_api_file_system_view(request, self.viewed)
assert FileSystemViewLog.objects.count() == expected_count
@@ -514,7 +516,7 @@ class TestLogApiFileSystemView(APIBaseTest):
request.COOKIES[settings.SESSION_COOKIE_NAME] = "session-key"
with patch("posthog.api.file_system.file_system_logging.is_impersonated_session", return_value=True):
- log_api_file_system_view(request, self.action)
+ log_api_file_system_view(request, self.viewed)
assert FileSystemViewLog.objects.count() == 0
@@ -637,7 +639,7 @@ class TestFileSystemDeletion(APIBaseTest):
assert flag.deleted is True
def test_deleting_non_last_copy_only_removes_entry(self) -> None:
- action = Action.objects.create(team=self.team, name="Delete action", created_by=self.user)
+ action = create_action(team=self.team, name="Delete action", created_by=self.user)
primary_entry = FileSystem.objects.get(team=self.team, type="action", ref=str(action.id))
duplicate_entry = FileSystem.objects.create(
team=self.team,
@@ -655,8 +657,7 @@ class TestFileSystemDeletion(APIBaseTest):
assert response.status_code == status.HTTP_204_NO_CONTENT
assert FileSystem.objects.filter(team=self.team, type="action", ref=str(action.id)).count() == 1
- action.refresh_from_db()
- assert action.deleted is False
+ assert get_action(action_id=action.id, team_id=self.team.id).deleted is False
assert FileSystem.objects.filter(id=primary_entry.id).exists()
def test_deleting_unknown_type_raises_error(self) -> None:
diff --git a/posthog/api/test/test_resource_transfer.py b/posthog/api/test/test_resource_transfer.py
index 5e246c533285..64d9ab4653ce 100644
--- a/posthog/api/test/test_resource_transfer.py
+++ b/posthog/api/test/test_resource_transfer.py
@@ -13,7 +13,7 @@ from posthog.models.resource_transfer.resource_transfer import ResourceTransfer
from posthog.models.scoping import team_scope
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
@@ -168,7 +168,7 @@ class TestResourceTransferPreview(APIBaseTest):
def test_preview_survey_includes_insight_and_dependencies(self) -> None:
insight = Insight.objects.create(team=self.team, name="Survey insight")
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="survey trigger",
steps_json=[{"event": "$pageview"}],
@@ -180,7 +180,7 @@ class TestResourceTransferPreview(APIBaseTest):
questions=[{"id": "q1", "type": "open", "question": "Hi"}],
linked_insight=insight,
)
- survey.actions.add(action)
+ survey.actions.add(action.id)
response = self.client.post(
self._preview_url(),
@@ -765,11 +765,11 @@ class TestResourceTransferTenantIsolation(APIBaseTest):
return f"/api/organizations/{self.organization.id}/resource_transfers/transfer/"
def test_preview_rejects_insight_referencing_foreign_org_action(self) -> None:
- foreign_action = Action.objects.create(team=self.foreign_team, name="Secret action")
+ foreign_action = create_action(team=self.foreign_team, name="Secret action")
insight = Insight.objects.create(
team=self.team,
name="Malicious insight",
- filters={"actions": [{"id": foreign_action.pk}]},
+ filters={"actions": [{"id": foreign_action.id}]},
)
response = self.client.post(
diff --git a/posthog/api/test/test_search.py b/posthog/api/test/test_search.py
index 12a6286c47e1..35d17e2086cb 100644
--- a/posthog/api/test/test_search.py
+++ b/posthog/api/test/test_search.py
@@ -368,8 +368,8 @@ class TestSearch(APIBaseTest):
)
assert len(ctx_with) - len(ctx_without) >= 13
- # One query for the unioned entities, one for the workflows merged in through the facade.
- assert len(ctx_without) == 2
+ # One query for the unioned entities, and one each for the actions and workflows merged in through their facades.
+ assert len(ctx_without) == 3
def test_search_entities_returns_total_count(self):
for i in range(5):
diff --git a/posthog/hogql/database/schema/test/test_flag_evaluations.py b/posthog/hogql/database/schema/test/test_flag_evaluations.py
index 8a385131fb6f..24577a06cb63 100644
--- a/posthog/hogql/database/schema/test/test_flag_evaluations.py
+++ b/posthog/hogql/database/schema/test/test_flag_evaluations.py
@@ -63,7 +63,7 @@ from posthog.test.persons import create_group_type_mapping, create_person
from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.access_control.backend.property_access_control import PropertyAccessLevel
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.util import insert_static_cohort
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
@@ -1262,8 +1262,8 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):
self._query_events("SELECT distinct_id FROM calls")
def test_view_that_names_flag_calls_only_through_an_action_raises(self):
- action = Action.objects.create(team=self.team, steps_json=[{"event": "$feature_flag_called"}])
- self._create_view("calls", f"SELECT distinct_id FROM events WHERE matchesAction({action.pk})")
+ action = create_action(team=self.team, steps_json=[{"event": "$feature_flag_called"}])
+ self._create_view("calls", f"SELECT distinct_id FROM events WHERE matchesAction({action.id})")
with self.assertRaisesRegex(QueryError, "it reads the saved view calls, which reads them from events"):
self._query_events("SELECT distinct_id FROM calls")
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index cd07b4324c16..71937429cbec 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -45,7 +45,7 @@ from products.access_control.backend.facade.contracts import PropertyAccessLevel
from products.access_control.backend.models.access_control import AccessControl
from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.access_control.backend.models.role import Role
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.aeo.backend.facade.testing import create_citation_check
from products.ai_observability.backend.models.datasets import Dataset, DatasetItem, DatasetItemVersion, DatasetRevision
from products.ai_observability.backend.models.evaluation_directories import EvaluationDirectory
@@ -396,8 +396,8 @@ def _create_feature_request_history(team: Team, label: str):
return create_feature_request_history(team_id=team.pk, feature_request=feature_request, changed_at=timezone.now())
-def _create_action(team: Team, label: str) -> Action:
- return Action.objects.create(team=team, name=f"action_{label}")
+def _create_action(team: Team, label: str) -> int:
+ return create_action(team=team, name=f"action_{label}").id
def _create_cohort(team: Team, label: str) -> Cohort:
diff --git a/posthog/hogql/functions/action.py b/posthog/hogql/functions/action.py
index d9daedab503d..fa05ff02979d 100644
--- a/posthog/hogql/functions/action.py
+++ b/posthog/hogql/functions/action.py
@@ -13,28 +13,28 @@ def matches_action(node: ast.Expr, args: list[ast.Expr], context: HogQLContext,
from posthog.hogql.property import action_to_expr
- from products.actions.backend.models.action import Action
+ from products.actions.backend.facade.api import find_actions_by_name, get_actions
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()
+ actions = get_actions(action_ids=[int(arg.value)], project_id=context.project_id)
if len(actions) == 1:
context.add_notice(
start=arg.start,
end=arg.end,
- message=f"Action #{actions[0].pk} can also be specified as {escape_clickhouse_string(actions[0].name)}",
+ message=f"Action #{actions[0].id} can also be specified as {escape_clickhouse_string(actions[0].name)}",
fix=escape_clickhouse_string(actions[0].name),
)
return action_to_expr(actions[0], events_alias=events_alias)
raise QueryError(f"Could not find an action with ID {arg.value}", node=arg)
if isinstance(arg.value, str):
- actions = Action.objects.filter(name=arg.value, team__project_id=context.project_id).all()
+ actions = find_actions_by_name(name=arg.value, project_id=context.project_id, include_deleted=True)
if len(actions) == 1:
context.add_notice(
start=arg.start,
end=arg.end,
- message=f"Searching for action by name. Replace with numeric ID {actions[0].pk} to protect against renaming.",
- fix=str(actions[0].pk),
+ message=f"Searching for action by name. Replace with numeric ID {actions[0].id} to protect against renaming.",
+ fix=str(actions[0].id),
)
return action_to_expr(actions[0], events_alias=events_alias)
elif len(actions) > 1:
diff --git a/posthog/hogql/functions/test/test_action.py b/posthog/hogql/functions/test/test_action.py
index f7ed03422d91..7d079958170c 100644
--- a/posthog/hogql/functions/test/test_action.py
+++ b/posthog/hogql/functions/test/test_action.py
@@ -17,13 +17,13 @@ from posthog.hogql.test.utils import pretty_print_response_in_tests
from posthog.uuidt import UUIDT
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
def _create_action_with_property(**kwargs):
team = kwargs.pop("team")
name = kwargs.pop("name")
- action = Action.objects.create(
+ action = create_action(
team=team,
name=name,
steps_json=[
@@ -76,7 +76,7 @@ class TestAction(BaseTest, QueryMatchingTest):
random_uuid = self._create_random_events()
action = _create_action(team=self.team, name=random_uuid)
response = execute_hogql_query(
- f"SELECT event FROM events WHERE matchesAction({action.pk})",
+ f"SELECT event FROM events WHERE matchesAction({action.id})",
self.team,
)
assert response.results is not None
diff --git a/posthog/hogql/functions/test/test_traffic_type_functions.py b/posthog/hogql/functions/test/test_traffic_type_functions.py
index 948c139345fb..35bc5d9c8c87 100644
--- a/posthog/hogql/functions/test/test_traffic_type_functions.py
+++ b/posthog/hogql/functions/test/test_traffic_type_functions.py
@@ -26,7 +26,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.schema_enums import FilterLogicalOperator
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
from products.web_analytics.backend.hogql_queries.bot_ip_definitions import BOT_IP_DEFINITIONS
@@ -691,7 +691,7 @@ class TestMacroExpansionGuard(BaseTest):
# matchesAction expands a user-defined action, whose hogql property filters re-parse
# arbitrary user HogQL. A guarded macro referenced there must still expand — the guard
# must not fire across matchesAction's (bounded) action expansion.
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[
{
@@ -702,7 +702,7 @@ class TestMacroExpansionGuard(BaseTest):
}
],
)
- printed = self._print(f"SELECT matchesAction({action.pk}) FROM events")
+ printed = self._print(f"SELECT matchesAction({action.id}) FROM events")
assert "multiMatchAnyIndex" in printed
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.py
index 0d26d5e8b338..b16ed04a71f3 100644
--- a/posthog/hogql/property.py
+++ b/posthog/hogql/property.py
@@ -1,6 +1,6 @@
import re
import math
-from collections.abc import Callable
+from collections.abc import Callable, Sequence
from typing import Literal, Optional, TypeGuard, cast
from django.db import models
@@ -67,7 +67,8 @@ from posthog.models.property import BehavioralPropertyType, PropertyGroup, Value
from posthog.models.property.util import build_selector_regex
from posthog.utils import get_from_dict_or_attr, relative_date_parse
-from products.actions.backend.models.action import Action, ActionStepJSON
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import Action, ActionNotFound, ActionStep
from products.cohorts.backend.models.cohort import Cohort
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.event_definitions.backend.models.property_definition import PropertyType
@@ -1135,8 +1136,8 @@ def _behavioral_property_to_expr(property: Property, team: Team, scope: str, str
if property.event_type == "actions":
try:
- action = Action.objects.get(pk=int(property.key), team__project_id=team.project_id)
- except (Action.DoesNotExist, ValueError, TypeError):
+ action = get_action(action_id=int(property.key), project_id=team.project_id)
+ except (ActionNotFound, ValueError, TypeError):
raise QueryError(f"Action '{property.key}' in behavioral filter not found")
conditions: list[ast.Expr] = [action_to_expr(action)]
else:
@@ -1829,7 +1830,7 @@ def bound_property_to_expr(property: Property, expr: ast.Expr, team: Team) -> as
)
-def steps_to_expr(steps: list[ActionStepJSON], team: Team, events_alias: Optional[str] = None) -> ast.Expr:
+def steps_to_expr(steps: Sequence[ActionStep], team: Team, events_alias: Optional[str] = None) -> ast.Expr:
if len(steps) == 0:
return ast.Constant(value=True)
@@ -1954,8 +1955,18 @@ def steps_to_expr(steps: list[ActionStepJSON], team: Team, events_alias: Optiona
return ast.Or(exprs=or_queries)
-def action_to_expr(action: Action, events_alias: Optional[str] = None) -> ast.Expr:
- return steps_to_expr(action.steps, action.team, events_alias)
+def action_to_expr(action: Action, events_alias: Optional[str] = None, *, team: Optional[Team] = None) -> ast.Expr:
+ """The condition an event must meet to match the action, compiled against the action's own team.
+
+ The action's team is read by id. A caller that holds that team, or a child environment of it, can
+ pass it as `team` to skip the read; any other team is not used. Actions live on the project's root
+ team, so a child environment reaches it through its cached `parent_team`.
+ """
+ if team is not None and team.pk != action.team_id and team.parent_team_id == action.team_id:
+ team = team.parent_team
+ if team is None or team.pk != action.team_id:
+ team = Team.objects.get(pk=action.team_id)
+ return steps_to_expr(action.steps, team, events_alias)
def entity_to_expr(entity: RetentionEntity, team: Team) -> ast.Expr:
@@ -1963,8 +1974,8 @@ def entity_to_expr(entity: RetentionEntity, team: Team) -> ast.Expr:
# action
action_id = int(entity.id) if isinstance(entity.id, float) else entity.id
try:
- action = Action.objects.get(pk=action_id, team=team)
- except Action.DoesNotExist:
+ action = get_action(action_id=int(action_id), team_id=team.pk)
+ except ActionNotFound:
raise ValidationError(f"Action ID {entity.id} does not exist!")
event_expr = action_to_expr(action)
elif entity.id is None:
diff --git a/posthog/hogql/test/test_action_to_expr.py b/posthog/hogql/test/test_action_to_expr.py
index 6a29d9e24c95..17af2957b4e2 100644
--- a/posthog/hogql/test/test_action_to_expr.py
+++ b/posthog/hogql/test/test_action_to_expr.py
@@ -12,7 +12,8 @@ from posthog.hogql.visitor import clear_locations
from posthog.models import Team
-from products.actions.backend.models.action import Action, ActionStepJSON
+from products.actions.backend.facade.contracts import ActionStep
+from products.actions.backend.facade.testing import create_action
class TestActionToExpr(BaseTest):
@@ -26,7 +27,7 @@ class TestActionToExpr(BaseTest):
_create_event(
event="$autocapture", team=self.team, distinct_id="some_id", elements_chain='a.active.nav-link:text="text"'
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[
{
@@ -63,7 +64,7 @@ class TestActionToExpr(BaseTest):
def test_action_to_expr_pageview_url_contains(self):
"""Test pageview action with URL contains matching"""
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[
{
@@ -80,7 +81,7 @@ class TestActionToExpr(BaseTest):
def test_action_to_expr_multiple_steps_or(self):
"""Test action with multiple steps creating OR expression"""
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[
{
@@ -108,7 +109,7 @@ class TestActionToExpr(BaseTest):
def test_action_to_expr_null_event_resolves_to_true(self):
"""Test action with null event step resolves to true"""
- action = Action.objects.create(team=self.team, steps_json=[{"event": "$pageview"}, {"event": None}])
+ action = create_action(team=self.team, steps_json=[{"event": "$pageview"}, {"event": None}])
self.assertEqual(
clear_locations(action_to_expr(action)),
self._parse_expr("event = '$pageview' OR true"),
@@ -116,7 +117,7 @@ class TestActionToExpr(BaseTest):
def test_action_to_expr_autocapture_href_regex(self):
"""Test autocapture action with href regex matching"""
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[{"event": "$autocapture", "href": "https://example4.com", "href_matching": "regex"}],
)
@@ -127,7 +128,7 @@ class TestActionToExpr(BaseTest):
def test_action_to_expr_autocapture_text_regex(self):
"""Test autocapture action with text regex matching"""
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[{"event": "$autocapture", "text": "blabla", "text_matching": "regex"}],
)
@@ -138,7 +139,7 @@ class TestActionToExpr(BaseTest):
def test_action_to_expr_autocapture_text_contains(self):
"""Test autocapture action with text contains matching"""
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[{"event": "$autocapture", "text": "blabla", "text_matching": "contains"}],
)
@@ -149,7 +150,7 @@ class TestActionToExpr(BaseTest):
def test_action_to_expr_autocapture_text_exact(self):
"""Test autocapture action with text exact matching"""
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[{"event": "$autocapture", "text": "blabla", "text_matching": "exact"}],
)
@@ -159,7 +160,7 @@ class TestActionToExpr(BaseTest):
)
def test_steps_to_expr_matches_action_to_expr(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[
{"event": "$pageview", "url": "https://example.com", "url_matching": "contains"},
@@ -167,8 +168,8 @@ class TestActionToExpr(BaseTest):
],
)
steps = [
- ActionStepJSON(event="$pageview", url="https://example.com", url_matching="contains"),
- ActionStepJSON(event="custom_event"),
+ ActionStep(event="$pageview", url="https://example.com", url_matching="contains"),
+ ActionStep(event="custom_event"),
]
self.assertEqual(
clear_locations(action_to_expr(action)),
@@ -186,14 +187,14 @@ class TestStepsToExprRegexValidation:
@pytest.mark.parametrize(
"step",
[
- ActionStepJSON(event="$pageview", url="/token-abc123/\\d+\\", url_matching="regex"),
- ActionStepJSON(event="$autocapture", href="/token-abc123/\\d+\\", href_matching="regex"),
- ActionStepJSON(event="$autocapture", text="/token-abc123/\\d+\\", text_matching="regex"),
+ ActionStep(event="$pageview", url="/token-abc123/\\d+\\", url_matching="regex"),
+ ActionStep(event="$autocapture", href="/token-abc123/\\d+\\", href_matching="regex"),
+ ActionStep(event="$autocapture", text="/token-abc123/\\d+\\", text_matching="regex"),
],
ids=["url", "href", "text"],
)
def test_invalid_step_regex_raises_query_error_without_logging_it(
- self, step: ActionStepJSON, capfd: pytest.CaptureFixture[str]
+ self, step: ActionStep, capfd: pytest.CaptureFixture[str]
) -> None:
with pytest.raises(QueryError, match="Invalid regular expression"):
steps_to_expr([step], team=Team())
diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.py
index 6eb8fefdb7fd..2b173feab858 100644
--- a/posthog/hogql/test/test_property.py
+++ b/posthog/hogql/test/test_property.py
@@ -3,7 +3,7 @@ from typing import Any, Literal, Optional, Union, cast
import time_machine
from posthog.test.base import APIBaseTest, BaseTest, _create_event, cleanup_materialized_columns
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
from django.conf import settings
from django.test import SimpleTestCase, override_settings
@@ -51,7 +51,7 @@ from posthog.models.property import PropertyGroup
from posthog.models.property.util import get_property_string_expr
from posthog.utils import relative_date_parse
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.cohorts.backend.models.cohort import Cohort
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.event_definitions.backend.models.property_definition import PropertyType
@@ -1220,11 +1220,10 @@ class TestProperty(BaseTest):
assert "pdi" not in sql
def test_entity_to_expr_actions_type_with_id(self):
- action_mock = MagicMock()
- 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)
+ action = create_action(team=self.team, steps_json=[{"event": "$pageview"}])
+ entity = RetentionEntity(**{"type": TREND_FILTER_TYPE_ACTIONS, "id": action.id})
+ result = entity_to_expr(entity, self.team)
+ self.assertIsInstance(result, ast.Expr)
def test_entity_to_expr_events_type_with_id(self):
entity = RetentionEntity(**{"type": TREND_FILTER_TYPE_EVENTS, "id": "event_id"})
@@ -2475,9 +2474,9 @@ class TestProperty(BaseTest):
self._property_to_expr(self._behavioral_filter(event_type="actions", key="999999"))
def test_behavioral_performed_event_with_action(self):
- action = Action.objects.create(team=self.team, steps_json=[{"event": "$pageview"}])
+ action = create_action(team=self.team, steps_json=[{"event": "$pageview"}])
self.assertEqual(
- self._property_to_expr(self._behavioral_filter(event_type="actions", key=str(action.pk))),
+ self._property_to_expr(self._behavioral_filter(event_type="actions", key=str(action.id))),
self._parse_expr(
"person_id IN (SELECT person_id FROM events WHERE {action}"
" AND timestamp > now() - toIntervalDay(30) GROUP BY person_id)",
@@ -2487,14 +2486,16 @@ class TestProperty(BaseTest):
def test_behavioral_property_in_action_step_raises(self):
# Compiling one would re-enter action_to_expr until Python's recursion limit
- action = Action.objects.create(team=self.team, steps_json=[{"event": "$pageview"}])
- action.steps_json = [
- {
- "event": "$pageview",
- "properties": [self._behavioral_filter(event_type="actions", key=str(action.pk))],
- }
- ]
- action.save()
+ action = create_action(team=self.team, steps_json=[{"event": "$pageview"}])
+ action = update_action(
+ action,
+ steps_json=[
+ {
+ "event": "$pageview",
+ "properties": [self._behavioral_filter(event_type="actions", key=str(action.id))],
+ }
+ ],
+ )
with self.assertRaises(QueryError):
action_to_expr(action)
diff --git a/posthog/hogql/test/test_trino_semantics.py b/posthog/hogql/test/test_trino_semantics.py
index 09dd3a47c440..5bdd062a86e1 100644
--- a/posthog/hogql/test/test_trino_semantics.py
+++ b/posthog/hogql/test/test_trino_semantics.py
@@ -19,7 +19,7 @@ from posthog.schema_enums import InCohortVia, InlineCohortCalculation, PersonsOn
from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.access_control.backend.property_access_control import PropertyAccessLevel
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
@@ -52,7 +52,7 @@ class TestTrinoSemantics(APIBaseTest):
)
def test_action_semantics_expand_before_trino_printing(self) -> None:
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="completed checkout",
steps_json=[{"event": "checkout completed"}],
@@ -61,7 +61,7 @@ class TestTrinoSemantics(APIBaseTest):
sql, node = prepare_and_print_ast(
parse_select(
- f"SELECT event, count() AS total FROM events WHERE matchesAction({action.pk}) "
+ f"SELECT event, count() AS total FROM events WHERE matchesAction({action.id}) "
"GROUP BY event ORDER BY total DESC LIMIT 1 BY event"
),
context,
diff --git a/posthog/hogql_queries/ai/event_taxonomy_query_runner.py b/posthog/hogql_queries/ai/event_taxonomy_query_runner.py
index f7cde1ab24f1..29ef5db1366b 100644
--- a/posthog/hogql_queries/ai/event_taxonomy_query_runner.py
+++ b/posthog/hogql_queries/ai/event_taxonomy_query_runner.py
@@ -18,7 +18,7 @@ from posthog.hogql_queries.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.models.event.new_events_schema import use_new_events_schema
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
DEFAULT_LIMIT = 500
@@ -158,7 +158,7 @@ class EventTaxonomyQueryRunner(TaxonomyCacheMixin, AnalyticsQueryRunner[EventTax
)
)
elif self.query.actionId:
- action = Action.objects.get(pk=self.query.actionId, team__project_id=self.team.project_id)
+ action = get_action(action_id=self.query.actionId, project_id=self.team.project_id)
filter_expr.append(action_to_expr(action))
else:
raise ValueError("Either event or action ID must be provided.")
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 972533ecf178..6c1d1617e4c1 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
@@ -21,7 +21,7 @@ from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql_queries.ai.event_taxonomy_query_runner import EventTaxonomyQueryRunner
from posthog.models import PropertyDefinition
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.event_definitions.backend.models.property_definition import PropertyType
@@ -535,7 +535,7 @@ class TestEventTaxonomyQueryRunner(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_retrieves_action_properties(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="action1",
steps_json=[{"event": "$pageview"}],
diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.py
index ebbcc07348dd..d75dfa34d050 100644
--- a/posthog/hogql_queries/events_query_runner.py
+++ b/posthog/hogql_queries/events_query_runner.py
@@ -62,7 +62,8 @@ from posthog.models.person.util import get_person_by_pk_or_uuid, get_persons_map
from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.utils import relative_date_parse
-from products.actions.backend.models.action import Action, ActionStepJSON
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound, ActionStep
from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.facade.flags import get_flag_evaluations_read_mode
@@ -551,8 +552,8 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
def _action_where_expr(self, action_id: int) -> ast.Expr:
try:
- action = Action.objects.get(pk=action_id, team__project_id=self.team.project_id)
- except Action.DoesNotExist:
+ action = get_action(action_id=action_id, project_id=self.team.project_id)
+ except ActionNotFound:
raise Exception("Action does not exist")
if not action.steps:
raise Exception("Action does not have any match groups")
@@ -560,7 +561,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
def _action_steps_where_expr(self) -> ast.Expr:
steps = [
- ActionStepJSON(
+ ActionStep(
event=s.event,
tag_name=s.tag_name,
text=s.text,
diff --git a/posthog/hogql_queries/properties_timeline/properties_timeline.py b/posthog/hogql_queries/properties_timeline/properties_timeline.py
index 02bd351c433d..60263c1211f1 100644
--- a/posthog/hogql_queries/properties_timeline/properties_timeline.py
+++ b/posthog/hogql_queries/properties_timeline/properties_timeline.py
@@ -28,7 +28,7 @@ from posthog.models.person.person import Person
from posthog.models.property.util import count_hogql_properties
from posthog.models.team.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_actions
from products.product_analytics.backend.facade import queries as product_analytics_queries
@@ -180,8 +180,8 @@ class PropertiesTimeline:
# Only the series' event or action selects events. Its property filters name key properties,
# and filtering on them would hide the changes the timeline shows.
if isinstance(series, ActionsNode):
- action = Action.objects.filter(pk=series.id, team__project_id=team.project_id).first()
- return action_to_expr(action) if action is not None else ast.Constant(value=False)
+ actions = get_actions(action_ids=[series.id], project_id=team.project_id)
+ return action_to_expr(actions[0]) if actions else ast.Constant(value=False)
if series.event is None:
return None
return ast.CompareOperation(
diff --git a/posthog/hogql_queries/query_metadata.py b/posthog/hogql_queries/query_metadata.py
index 819b567df6f9..0b265e56ee9e 100644
--- a/posthog/hogql_queries/query_metadata.py
+++ b/posthog/hogql_queries/query_metadata.py
@@ -40,7 +40,8 @@ from posthog.cache_utils import cache_for
from posthog.models import Team
from posthog.utils import get_from_dict_or_attr
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
T = TypeVar("T", bound=BaseModel)
@@ -221,9 +222,9 @@ class QueryEventsExtractor:
@cache_for(timedelta(minutes=1))
def _get_action_events(action_id: int, project_id: int) -> list[str]:
try:
- action = Action.objects.get(pk=action_id, team__project_id=project_id)
+ action = get_action(action_id=action_id, project_id=project_id)
return [event for event in action.get_step_events() if event is not None]
- except Action.DoesNotExist:
+ except ActionNotFound:
return []
diff --git a/posthog/hogql_queries/sessions_query_runner.py b/posthog/hogql_queries/sessions_query_runner.py
index 1a874ba482ac..601115faf1e4 100644
--- a/posthog/hogql_queries/sessions_query_runner.py
+++ b/posthog/hogql_queries/sessions_query_runner.py
@@ -30,7 +30,8 @@ from posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORS
from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.utils import relative_date_parse
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
COLUMN_COMMENT_SEPARATOR = " -- "
SUPPORTED_PERSON_PROPERTY_OPERATORS = frozenset(
@@ -434,10 +435,8 @@ class SessionsQueryRunner(AnalyticsQueryRunner[SessionsQueryResponse]):
)
elif self.query.actionId:
try:
- action = Action.objects.get(
- pk=self.query.actionId, team__project_id=self.team.project_id
- )
- except Action.DoesNotExist:
+ action = get_action(action_id=self.query.actionId, project_id=self.team.project_id)
+ except ActionNotFound:
raise Exception("Action does not exist")
if not action.steps:
raise Exception("Action does not have any match groups")
diff --git a/posthog/hogql_queries/test/test_query_metadata.py b/posthog/hogql_queries/test/test_query_metadata.py
index ffd488e138e4..035dc0e3309a 100644
--- a/posthog/hogql_queries/test/test_query_metadata.py
+++ b/posthog/hogql_queries/test/test_query_metadata.py
@@ -31,7 +31,7 @@ from posthog.schema import (
from posthog.hogql_queries.query_metadata import QueryEventsExtractor
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import ActionNotFound
class TestQueryEventsExtractor(TestCase):
@@ -58,7 +58,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["pageview", "click"])
- @patch("products.actions.backend.models.action.Action.objects.get")
+ @patch("posthog.hogql_queries.query_metadata.get_action")
def test_extract_events_with_actions_node(self, mock_action_get):
"""Test extracting events from query with ActionsNode"""
mock_action = Mock()
@@ -74,7 +74,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["pageview", "signup", "purchase"])
- @patch("products.actions.backend.models.action.Action.objects.get")
+ @patch("posthog.hogql_queries.query_metadata.get_action")
def test_extract_events_with_actions_node_with_none_steps(self, mock_action_get):
"""Test extracting events from query with ActionsNode"""
mock_action = Mock()
@@ -90,10 +90,10 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["pageview", "signup"])
- @patch("products.actions.backend.models.action.Action.objects.get")
+ @patch("posthog.hogql_queries.query_metadata.get_action")
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
+ mock_action_get.side_effect = ActionNotFound
query = TrendsQuery(
series=[
ActionsNode(id=999), # Non-existent action ID
@@ -104,7 +104,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, [])
- mock_action_get.assert_called_once_with(pk=999, team__project_id=self.team.project_id)
+ mock_action_get.assert_called_once_with(action_id=999, project_id=self.team.project_id)
def test_extract_events_stickiness_query(self):
"""Test extracting events from StickinessQuery"""
@@ -179,7 +179,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["signup", "purchase", "abandon_cart", "logout"])
- @patch("products.actions.backend.models.action.Action.objects.get")
+ @patch("posthog.hogql_queries.query_metadata.get_action")
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()
@@ -222,7 +222,7 @@ class TestQueryEventsExtractor(TestCase):
result = self.extractor.extract_events(query)
self.assertCountEqual(result, ["signup", "purchase"])
- @patch("products.actions.backend.models.action.Action.objects.get")
+ @patch("posthog.hogql_queries.query_metadata.get_action")
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/result_series.py b/posthog/hogql_queries/utils/result_series.py
index b19d5a6a69da..005b83551514 100644
--- a/posthog/hogql_queries/utils/result_series.py
+++ b/posthog/hogql_queries/utils/result_series.py
@@ -8,7 +8,7 @@ Queries, rows and series nodes are JSON-shaped, as stored on an insight or dumpe
from collections.abc import Iterator, Mapping
from typing import TYPE_CHECKING, Any
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade import api as actions_facade
if TYPE_CHECKING:
from posthog.models import Team
@@ -58,7 +58,7 @@ def get_action_names(team: "Team", query: Mapping[str, Any]) -> dict[int, str |
action_ids = {action_id for node in _series_nodes(query) if (action_id := _action_id(node)) is not None}
if not action_ids:
return {}
- return dict(Action.objects.filter(pk__in=action_ids, team__project_id=team.project_id).values_list("pk", "name"))
+ return actions_facade.get_action_names(project_id=team.project_id, action_ids=action_ids)
def get_response_action_names(team: "Team", query: Mapping[str, Any]) -> dict[str, str] | None:
diff --git a/posthog/hogql_queries/utils/test/test_timestamp_utils.py b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
index 7157cda05591..ad9240a676a7 100644
--- a/posthog/hogql_queries/utils/test/test_timestamp_utils.py
+++ b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
@@ -38,7 +38,7 @@ from posthog.models.event.new_events_schema import events_route_scope
from posthog.models.instance_setting import override_instance_config
from posthog.models.team import WeekStartDay
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobStatus, DataWarehouseSavedQuery
@@ -290,8 +290,8 @@ class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):
def test_returns_earliest_timestamp_multiple_actions(self):
"""Test that multiple actions return the earliest timestamp across all actions"""
- action1 = Action.objects.create(team=self.team, name="Action 1", steps_json=[{"event": "$pageview"}])
- action2 = Action.objects.create(team=self.team, name="Action 2", steps_json=[{"event": "$pageleave"}])
+ action1 = create_action(team=self.team, name="Action 1", steps_json=[{"event": "$pageview"}])
+ action2 = create_action(team=self.team, name="Action 2", steps_json=[{"event": "$pageleave"}])
_create_event(
team=self.team,
@@ -313,7 +313,7 @@ class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):
def test_returns_earliest_timestamp_mixed_nodes(self):
"""Test that mixing EventsNode and ActionsNode returns earliest timestamp across all"""
- action = Action.objects.create(team=self.team, name="Action 1", steps_json=[{"event": "$pageview"}])
+ action = create_action(team=self.team, name="Action 1", steps_json=[{"event": "$pageview"}])
_create_event(
team=self.team,
diff --git a/posthog/hogql_queries/utils/timestamp_utils.py b/posthog/hogql_queries/utils/timestamp_utils.py
index 960f1dbb5114..872472bdff9e 100644
--- a/posthog/hogql_queries/utils/timestamp_utils.py
+++ b/posthog/hogql_queries/utils/timestamp_utils.py
@@ -37,7 +37,7 @@ from posthog.models.event.new_events_schema import get_events_route, use_new_eve
from posthog.models.team import WeekStartDay
from posthog.utils import get_safe_cache
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
from products.data_modeling.backend.facade import api as data_modeling_api
EARLIEST_TIMESTAMP_CACHE_TTL = 24 * 60 * 60
@@ -92,7 +92,7 @@ def _get_event_earliest_timestamp_query(team: Team, node: Union[EventsNode, Acti
]
if isinstance(node, ActionsNode):
- action = Action.objects.get(pk=node.id, team=team)
+ action = get_action(action_id=node.id, team_id=team.pk)
where_exprs.append(action_to_expr(action))
elif isinstance(node, EventsNode) and node.event is not None:
where_exprs.append(
diff --git a/posthog/management/commands/test/test_migrate_hooks.py b/posthog/management/commands/test/test_migrate_hooks.py
index f132c7354925..b720aab13d6a 100644
--- a/posthog/management/commands/test/test_migrate_hooks.py
+++ b/posthog/management/commands/test/test_migrate_hooks.py
@@ -2,7 +2,8 @@ from posthog.test.base import BaseTest
from posthog.management.commands.migrate_hooks import migrate_hooks
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action
from products.cdp.backend.filters import RUNTIME_CONTRACT
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.models.hook import Hook
@@ -18,7 +19,7 @@ class TestMigrateHooks(BaseTest):
def setUp(self):
super().setUp()
- self.action = Action.objects.create(
+ self.action = create_action(
created_by=self.user,
name="Test Action",
team_id=self.team.id,
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 3b30ac7fff11..10f92ead5b2d 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -70,7 +70,7 @@ from posthog.user_permissions import UserPermissions
from posthog.utils import get_ip_address, get_trusted_client_ip
from products.access_control.backend.facade.user_access_control import UserAccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import find_action_team_id
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -449,6 +449,10 @@ class AutoProjectMiddleware:
target_queryset = self.get_target_queryset(request)
if target_queryset is not None:
self.switch_team_if_needed_and_allowed(request, target_queryset)
+ else:
+ target_team_id = self.get_target_team_id(request)
+ if target_team_id is not None:
+ self.switch_to_team_id_if_needed_and_allowed(request, target_team_id)
return self.get_response(request)
def get_target_queryset(self, request: HttpRequest) -> Optional[QuerySet]:
@@ -473,11 +477,6 @@ class AutoProjectMiddleware:
if feature_flag_id.isnumeric():
# nosemgrep: idor-lookup-without-team (permission check via middleware prevents access)
return FeatureFlag.objects.filter(id=feature_flag_id)
- elif path_parts[0] == "action":
- action_id = path_parts[1]
- if action_id.isnumeric():
- # nosemgrep: idor-lookup-without-team (permission check via middleware prevents access)
- return Action.objects.filter(deleted=False, id=action_id)
elif path_parts[0] == "cohorts":
cohort_id = path_parts[1]
if cohort_id.isnumeric():
@@ -485,6 +484,23 @@ class AutoProjectMiddleware:
return Cohort.objects.filter(deleted=False, id=cohort_id)
return None
+ def get_target_team_id(self, request: HttpRequest) -> Optional[int]:
+ """The team owning the object a legacy app path names, for objects read through a product facade."""
+ path_parts = request.path.strip("/").split("/")
+ # Sync the paths with urls.ts!
+ if len(path_parts) >= 2 and path_parts[0] == "action" and path_parts[1].isnumeric():
+ # The permission check in switch_team_if_allowed guards the switch, so the lookup is unscoped.
+ return find_action_team_id(action_id=int(path_parts[1]), include_deleted=False)
+ return None
+
+ def switch_to_team_id_if_needed_and_allowed(self, request: HttpRequest, target_team_id: int) -> None:
+ user = cast(User, request.user)
+ current_team = user.team
+ if current_team is not None and current_team.pk != target_team_id:
+ target_team = Team.objects.filter(pk=target_team_id).first()
+ if target_team is not None:
+ self.switch_team_if_allowed(target_team, request)
+
def switch_team_if_needed_and_allowed(self, request: HttpRequest, target_queryset: QuerySet):
user = cast(User, request.user)
current_team = user.team
diff --git a/posthog/migrations/0410_action_steps_population.py b/posthog/migrations/0410_action_steps_population.py
index 1d6f8b7ee02c..9b35693392eb 100644
--- a/posthog/migrations/0410_action_steps_population.py
+++ b/posthog/migrations/0410_action_steps_population.py
@@ -5,7 +5,8 @@ from django.db import migrations
def copy_action_steps_to_json(apps, schema_editor):
- from products.actions.backend.models.action import Action
+ # The model as it stood at this migration, from the historical registry rather than the live code.
+ Action = apps.get_model("posthog", "Action")
all_actions_with_steps = Action.objects.prefetch_related("action_steps").order_by("pk").all()
@@ -32,7 +33,8 @@ def copy_action_steps_to_json(apps, schema_editor):
}
for step in action.action_steps.all()
]
- action.steps = new_steps
+ # Every step key in field order, which is what the model's `steps` setter stored.
+ action.steps_json = new_steps
objects_to_update.append(action)
diff --git a/posthog/models/event/legacy_events_query.py b/posthog/models/event/legacy_events_query.py
index 494ad3d459fd..b9497b95ab58 100644
--- a/posthog/models/event/legacy_events_query.py
+++ b/posthog/models/event/legacy_events_query.py
@@ -24,7 +24,8 @@ from posthog.models.team import Team
from posthog.models.user import User
from posthog.utils import generate_short_id, relative_date_parse
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
# Columns the events list/retrieve endpoints read. The order is the contract for zipping HogQL
# result rows back into the dict shape `ClickhouseEventSerializer` expects. Deliberately NOT "*":
@@ -267,8 +268,8 @@ class LegacyEventsListQuery:
# is left to fail (int() raises) — bad input should error, not silently return nothing.
if action_id:
try:
- action = Action.objects.get(pk=int(action_id), team__project_id=self.team.project_id)
- except Action.DoesNotExist:
+ action = get_action(action_id=int(action_id), project_id=self.team.project_id)
+ except ActionNotFound:
return [], False, applied_window_seconds
if not action.steps:
return [], False, applied_window_seconds
diff --git a/posthog/models/file_system/unfiled_file_saver.py b/posthog/models/file_system/unfiled_file_saver.py
index 82fb925c7465..f31294981a75 100644
--- a/posthog/models/file_system/unfiled_file_saver.py
+++ b/posthog/models/file_system/unfiled_file_saver.py
@@ -11,7 +11,6 @@ from posthog.models.team import Team
from posthog.models.user import User
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
-from products.actions.backend.models.action import Action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
@@ -21,8 +20,8 @@ from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.facade.models import Insight
from products.surveys.backend.models import Survey
+# Sealed products add their own models with `register_mixin_model` (actions, canvas, experiments).
MIXIN_MODELS: dict[str, type[FileSystemSyncMixin]] = {
- "action": Action,
"feature_flag": FeatureFlag,
"insight": Insight,
"dashboard": Dashboard,
diff --git a/posthog/models/property/util.py b/posthog/models/property/util.py
index a2de4b366349..2f096e7467a2 100644
--- a/posthog/models/property/util.py
+++ b/posthog/models/property/util.py
@@ -16,9 +16,10 @@ from posthog.clickhouse.kafka_engine import trim_quotes_expr
from posthog.clickhouse.materialized_columns import TableWithProperties, get_materialized_column_for_property
from posthog.models.event import Selector
from posthog.models.property import Property, PropertyGroup, PropertyIdentifier, PropertyName
+from posthog.models.property.parse import parse_property_group_data
-from products.actions.backend.models.action import Action
-from products.actions.backend.models.util import get_action_tables_and_properties
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import Action
def get_property_string_expr(
@@ -221,13 +222,27 @@ class HogQLPropertyChecker(TraversingVisitor):
self.person_properties.append(str(node.chain[3]))
+def get_action_tables_and_properties(action: Action) -> TCounter[PropertyIdentifier]:
+ result: TCounter[PropertyIdentifier] = Counter()
+
+ for action_step in action.steps:
+ if action_step.url:
+ result[("$current_url", "event", None)] += 1
+ result += extract_tables_and_properties(
+ parse_property_group_data(action_step.properties or []).flat,
+ team_id=action.team_id,
+ )
+
+ return result
+
+
def extract_tables_and_properties(props: list[Property], team_id: int) -> TCounter[PropertyIdentifier]:
counters: list[tuple] = []
for prop in props:
if prop.type == "hogql":
counters.extend(count_hogql_properties(prop.key))
elif prop.type == "behavioral" and prop.event_type == "actions":
- action = Action.objects.get(pk=prop.key, team_id=team_id)
+ action = get_action(action_id=int(prop.key), team_id=team_id)
action_counter = get_action_tables_and_properties(action)
counters.extend(action_counter)
else:
diff --git a/posthog/models/resource_transfer/registered_models.py b/posthog/models/resource_transfer/registered_models.py
new file mode 100644
index 000000000000..de3fb47a7f37
--- /dev/null
+++ b/posthog/models/resource_transfer/registered_models.py
@@ -0,0 +1,22 @@
+"""The model behind a resource kind, for a kind whose model lives in a sealed product.
+
+A sealed product names its model from its own `AppConfig.ready()`, so the visitors here never import
+the product's internals. This module stays light: products import it while Django sets up.
+"""
+
+from django.db import models
+
+from posthog.models.resource_transfer.types import ResourceKind
+
+_MODELS: dict[ResourceKind, type[models.Model]] = {}
+
+
+def register_model(kind: ResourceKind, model: type[models.Model]) -> None:
+ _MODELS[kind] = model
+
+
+def registered_model(kind: ResourceKind) -> type[models.Model]:
+ try:
+ return _MODELS[kind]
+ except KeyError:
+ raise LookupError(f"No model is registered for the resource kind {kind}") from None
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 dd17fa58f6b4..2721f5b36026 100644
--- a/posthog/models/resource_transfer/test/test_inter_project_transferer.py
+++ b/posthog/models/resource_transfer/test/test_inter_project_transferer.py
@@ -12,11 +12,12 @@ from posthog.models.resource_transfer.inter_project_transferer import (
duplicate_resource_to_new_team,
get_suggested_substitutions,
)
+from posthog.models.resource_transfer.registered_models import registered_model
from posthog.models.resource_transfer.resource_transfer import ResourceTransfer
from posthog.models.resource_transfer.types import ResourceKind, ResourceTransferVertex
from posthog.models.scoping import team_scope
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
from products.dashboards.backend.models.dashboard_widget import DashboardWidget
@@ -61,7 +62,7 @@ class TestBuildResourceDuplicationGraph(BaseTest):
def test_survey_with_insight_and_actions_includes_related_resources(self) -> None:
insight = Insight.objects.create(team=self.team, name="Survey insight")
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="survey action",
steps_json=[{"event": "$pageview"}],
@@ -73,7 +74,7 @@ class TestBuildResourceDuplicationGraph(BaseTest):
questions=[{"id": "q1", "type": "open", "question": "Hello"}],
linked_insight=insight,
)
- survey.actions.add(action)
+ survey.actions.add(action.id)
graph = list(build_resource_duplication_graph(survey, set()))
model_types = {v.model for v in graph}
@@ -81,7 +82,7 @@ class TestBuildResourceDuplicationGraph(BaseTest):
assert Survey in model_types
assert Insight in model_types
- assert Action in model_types
+ assert registered_model("Action") in model_types
assert through in model_types
assert Team in model_types
@@ -204,7 +205,7 @@ class TestDuplicateResourceToNewTeam(BaseTest):
def test_duplicates_survey_with_linked_insight_and_actions(self) -> None:
dest_team = self._create_destination_team()
insight = Insight.objects.create(team=self.team, name="Linked", filters={})
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="trigger action",
steps_json=[{"event": "subscribed"}],
@@ -217,12 +218,12 @@ class TestDuplicateResourceToNewTeam(BaseTest):
conditions={"linkedFlagVariant": "control", "url": "/p"},
linked_insight=insight,
)
- survey.actions.add(action)
+ survey.actions.add(action.id)
results = duplicate_resource_to_new_team(survey, dest_team, created_by=self.user)
new_surveys = [r for r in results if isinstance(r, Survey)]
new_insights = [r for r in results if isinstance(r, Insight)]
- new_actions = [r for r in results if isinstance(r, Action)]
+ new_actions = [r for r in results if isinstance(r, registered_model("Action"))]
assert len(new_surveys) == 1
assert len(new_insights) == 1
diff --git a/posthog/models/resource_transfer/test/test_visitors.py b/posthog/models/resource_transfer/test/test_visitors.py
index 5044103639ab..8c19af3c4a34 100644
--- a/posthog/models/resource_transfer/test/test_visitors.py
+++ b/posthog/models/resource_transfer/test/test_visitors.py
@@ -5,6 +5,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.models.resource_transfer.registered_models import registered_model
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
@@ -20,7 +21,6 @@ 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.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import ExperimentHoldout
@@ -1194,7 +1194,7 @@ class TestFeatureFlagVisitorDynamicEdges(SimpleTestCase):
by_model_pk = {(e.target_model, e.target_primary_key) for e in edges}
assert (Cohort, 7) in by_model_pk
- assert (Action, 11) in by_model_pk
+ assert (registered_model("Action"), 11) in by_model_pk
assert (ExperimentHoldout, 3) in by_model_pk
names = {e.name for e in edges}
@@ -1259,7 +1259,7 @@ class TestExperimentVisitorDynamicEdges(SimpleTestCase):
)
edges = ExperimentVisitor.get_dynamic_edges(exp)
by_model_pk = {(e.target_model, e.target_primary_key) for e in edges}
- assert (Action, 777) in by_model_pk
+ assert (registered_model("Action"), 777) in by_model_pk
assert any(e.name == "json_action:777" for e in edges)
@@ -1293,7 +1293,7 @@ class TestExperimentSavedMetricVisitorDynamicEdges(SimpleTestCase):
)
edges = ExperimentSavedMetricVisitor.get_dynamic_edges(metric)
by_model_pk = {(e.target_model, e.target_primary_key) for e in edges}
- assert (Action, 888) in by_model_pk
+ assert (registered_model("Action"), 888) in by_model_pk
assert (Cohort, 999) in by_model_pk
def test_non_dict_query_returns_no_edges(self) -> None:
diff --git a/posthog/models/resource_transfer/visitors/action.py b/posthog/models/resource_transfer/visitors/action.py
index 6fd6d0c6f814..d6f97f671d22 100644
--- a/posthog/models/resource_transfer/visitors/action.py
+++ b/posthog/models/resource_transfer/visitors/action.py
@@ -1,5 +1,6 @@
from django.db import models
+from posthog.models.resource_transfer.registered_models import registered_model
from posthog.models.resource_transfer.visitors.base import ResourceTransferVisitor
@@ -22,6 +23,5 @@ class ActionVisitor(
):
@classmethod
def get_model(cls) -> type[models.Model]:
- from products.actions.backend.models.action import Action
-
- return Action
+ # The actions product registers its model from its AppConfig.ready().
+ return registered_model("Action")
diff --git a/posthog/models/resource_transfer/visitors/cohort.py b/posthog/models/resource_transfer/visitors/cohort.py
index ff028b908764..1de014e7c926 100644
--- a/posthog/models/resource_transfer/visitors/cohort.py
+++ b/posthog/models/resource_transfer/visitors/cohort.py
@@ -4,6 +4,7 @@ from typing import Any
from django.db import models
+from posthog.models.resource_transfer.registered_models import registered_model
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 (
@@ -42,7 +43,6 @@ class CohortVisitor(
@classmethod
def get_dynamic_edges(cls, resource: Any) -> list[ResourceTransferEdge]:
- from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
cohort_ids = cls._extract_cohort_ids(resource.filters)
@@ -50,7 +50,9 @@ class CohortVisitor(
edges: list[ResourceTransferEdge] = []
edges.extend(build_edges_for_ids(cohort_ids, Cohort, "cohort", cls._rewrite_cohort_in_payload))
- edges.extend(build_edges_for_ids(action_ids, Action, "action", cls._rewrite_action_in_payload))
+ edges.extend(
+ build_edges_for_ids(action_ids, registered_model("Action"), "action", cls._rewrite_action_in_payload)
+ )
return edges
@classmethod
diff --git a/posthog/models/resource_transfer/visitors/experiment.py b/posthog/models/resource_transfer/visitors/experiment.py
index c49f1a521c24..8a97a7cc1024 100644
--- a/posthog/models/resource_transfer/visitors/experiment.py
+++ b/posthog/models/resource_transfer/visitors/experiment.py
@@ -4,6 +4,7 @@ from typing import Any
from django.db import models
+from posthog.models.resource_transfer.registered_models import registered_model
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
@@ -13,7 +14,6 @@ from posthog.models.resource_transfer.visitors.experiment_payload import (
rewrite_cohort_in_experiment_payload,
)
-from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
@@ -54,6 +54,8 @@ class ExperimentVisitor(
build_edges_for_ids(collected.cohort_ids, Cohort, "json_cohort", rewrite_cohort_in_experiment_payload)
)
edges.extend(
- build_edges_for_ids(collected.action_ids, Action, "json_action", rewrite_action_in_experiment_payload)
+ build_edges_for_ids(
+ collected.action_ids, registered_model("Action"), "json_action", rewrite_action_in_experiment_payload
+ )
)
return edges
diff --git a/posthog/models/resource_transfer/visitors/experiment_saved_metric.py b/posthog/models/resource_transfer/visitors/experiment_saved_metric.py
index 48d27aca75a5..4f3caf72344d 100644
--- a/posthog/models/resource_transfer/visitors/experiment_saved_metric.py
+++ b/posthog/models/resource_transfer/visitors/experiment_saved_metric.py
@@ -4,12 +4,12 @@ from typing import Any
from django.db import models
+from posthog.models.resource_transfer.registered_models import registered_model
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
from products.cohorts.backend.models.cohort import Cohort
@@ -36,7 +36,11 @@ class ExperimentSavedMetricVisitor(
edges: list[ResourceTransferEdge] = []
edges.extend(build_edges_for_ids(cohort_ids, Cohort, "cohort", _rewrite_cohort_in_saved_metric_payload))
- edges.extend(build_edges_for_ids(action_ids, Action, "action", _rewrite_action_in_saved_metric_payload))
+ edges.extend(
+ build_edges_for_ids(
+ action_ids, registered_model("Action"), "action", _rewrite_action_in_saved_metric_payload
+ )
+ )
return edges
diff --git a/posthog/models/resource_transfer/visitors/feature_flag.py b/posthog/models/resource_transfer/visitors/feature_flag.py
index cc348a9df7d2..3002eb9ccdff 100644
--- a/posthog/models/resource_transfer/visitors/feature_flag.py
+++ b/posthog/models/resource_transfer/visitors/feature_flag.py
@@ -4,6 +4,7 @@ from typing import Any
from django.db import models
+from posthog.models.resource_transfer.registered_models import registered_model
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
@@ -16,7 +17,6 @@ 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.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import ExperimentHoldout
@@ -51,7 +51,9 @@ class FeatureFlagVisitor(
edges: list[ResourceTransferEdge] = []
edges.extend(build_edges_for_ids(cohort_ids, Cohort, "cohort", rewrite_cohort_in_flag_payload))
- edges.extend(build_edges_for_ids(action_ids, Action, "action", rewrite_action_in_flag_payload))
+ edges.extend(
+ build_edges_for_ids(action_ids, registered_model("Action"), "action", rewrite_action_in_flag_payload)
+ )
holdout_id = get_holdout_id_from_flag_filters(filters)
if holdout_id is not None:
diff --git a/posthog/models/resource_transfer/visitors/insight.py b/posthog/models/resource_transfer/visitors/insight.py
index 5f7b17d6a86f..884c6ffbb19c 100644
--- a/posthog/models/resource_transfer/visitors/insight.py
+++ b/posthog/models/resource_transfer/visitors/insight.py
@@ -4,6 +4,7 @@ from typing import Any
from django.db import models
+from posthog.models.resource_transfer.registered_models import registered_model
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 (
@@ -38,14 +39,15 @@ class InsightVisitor(
@classmethod
def get_dynamic_edges(cls, resource: Any) -> list[ResourceTransferEdge]:
- from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
action_ids = cls._extract_action_ids(resource.filters, resource.query)
cohort_ids = cls._extract_cohort_ids(resource.filters, resource.query)
edges: list[ResourceTransferEdge] = []
- edges.extend(build_edges_for_ids(action_ids, Action, "action", cls._rewrite_action_in_payload))
+ edges.extend(
+ build_edges_for_ids(action_ids, registered_model("Action"), "action", cls._rewrite_action_in_payload)
+ )
edges.extend(build_edges_for_ids(cohort_ids, Cohort, "cohort", cls._rewrite_cohort_in_payload))
return edges
diff --git a/posthog/models/test/test_hog_function.py b/posthog/models/test/test_hog_function.py
index 2b998f9ca1f2..6196317a7d47 100644
--- a/posthog/models/test/test_hog_function.py
+++ b/posthog/models/test/test_hog_function.py
@@ -12,7 +12,7 @@ from posthog.models.file_system.file_system import FileSystem
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.cdp.backend.filters import RUNTIME_CONTRACT
from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
from products.cdp.backend.tasks.hog_functions import refresh_affected_hog_functions
@@ -78,14 +78,14 @@ class TestHogFunction(TestCase):
]
self.team.save()
- action = Action.objects.create(team=self.team, name="Test Action")
+ action = create_action(team=self.team, name="Test Action")
item = HogFunction.objects.create(
name="Test",
type=HogFunctionType.DESTINATION,
team=self.team,
filters={
"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}],
- "actions": [{"id": str(action.pk), "name": "Test Action", "type": "actions", "order": 1}],
+ "actions": [{"id": str(action.id), "name": "Test Action", "type": "actions", "order": 1}],
"filter_test_accounts": True,
},
)
@@ -95,7 +95,7 @@ class TestHogFunction(TestCase):
assert json_filters == {
"bytecode_contract": RUNTIME_CONTRACT,
"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}],
- "actions": [{"id": str(action.pk), "name": "Test Action", "type": "actions", "order": 1}],
+ "actions": [{"id": str(action.id), "name": "Test Action", "type": "actions", "order": 1}],
"filter_test_accounts": True,
"bytecode": [
"_H",
@@ -290,7 +290,7 @@ class TestHogFunctionsBackgroundReloading(TestCase, QueryMatchingTest):
self.user = user
self.org = org
- self.action = Action.objects.create(
+ self.action = create_action(
team=self.team,
name="Test Action",
steps_json=[
@@ -308,7 +308,7 @@ class TestHogFunctionsBackgroundReloading(TestCase, QueryMatchingTest):
],
)
- self.action2 = Action.objects.create(
+ self.action2 = create_action(
team=self.team,
name="Test Action",
steps_json=[
@@ -361,22 +361,26 @@ class TestHogFunctionsBackgroundReloading(TestCase, QueryMatchingTest):
)
# Modify the action and check that the bytecode is updated
- self.action.steps_json = [
- {
- "event": "test-event",
- "properties": [
+ # 2 reads by the test helper (the action, then its team for the save), then the save's own 12: 1 update
+ # action, 2 activity logging, 1 load action, 1 load hog functions, 1 load hog flows, 1 load all related
+ # actions, 1 bulk update hog functions, 5 filesystem
+ with self.assertNumQueries(14):
+ update_action(
+ self.action,
+ steps_json=[
{
- "key": "prop-1",
- "operator": "exact",
- "value": "change-value",
- "type": "event",
+ "event": "test-event",
+ "properties": [
+ {
+ "key": "prop-1",
+ "operator": "exact",
+ "value": "change-value",
+ "type": "event",
+ }
+ ],
}
],
- }
- ]
- # 1 update action, 2 activity logging, 1 load action, 1 load hog functions, 1 load hog flows, 1 load all related actions, 1 bulk update hog functions, 5 filesystem
- with self.assertNumQueries(12):
- self.action.save()
+ )
hog_function_1.refresh_from_db()
hog_function_2.refresh_from_db()
diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.py
index 4ac13a805df7..6c29c5132102 100644
--- a/posthog/models/test/test_remote_config.py
+++ b/posthog/models/test/test_remote_config.py
@@ -22,7 +22,7 @@ from posthog.models.remote_config import (
UnreadableTriggerGroupsError,
)
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.templates.helpers import mock_transpile
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -684,7 +684,7 @@ class TestRemoteConfigSurveys(_RemoteConfigBase):
start_date=timezone.now(),
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="user subscribed",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
@@ -698,7 +698,7 @@ class TestRemoteConfigSurveys(_RemoteConfigBase):
questions=[{"type": "open", "question": "Why's a hedgehog?"}],
start_date=timezone.now(),
)
- survey_with_actions.actions.set(Action.objects.filter(name="user subscribed"))
+ survey_with_actions.actions.set([action.id])
survey_with_actions.save()
self.sync_remote_config()
diff --git a/posthog/models/test/test_tagged_item_model.py b/posthog/models/test/test_tagged_item_model.py
index 8e271a1c4ff2..37b9f716198b 100644
--- a/posthog/models/test/test_tagged_item_model.py
+++ b/posthog/models/test/test_tagged_item_model.py
@@ -1,3 +1,5 @@
+from collections.abc import Callable
+
from posthog.test.base import BaseTest
from django.contrib.contenttypes.models import ContentType
@@ -7,9 +9,10 @@ from django.db import models
from parameterized import parameterized
from posthog.models import Tag, TaggedItem, Team
+from posthog.models.tagged_item_registry import content_type_id_for_legacy_field
from posthog.models.tagged_items_relation import Taggable
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.dashboards.backend.models.dashboard import Dashboard
from products.event_definitions.backend.models import EventDefinition
from products.product_analytics.backend.facade.models import Insight
@@ -21,9 +24,16 @@ class TestTaggedItem(BaseTest):
return Dashboard.objects.create(team_id=self.team.id, name="dashboard")
if kind == "insight":
return Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)
- if kind == "event_definition":
- return EventDefinition.objects.create(team=self.team, name="event")
- return Action.objects.create(team=self.team, name="action")
+ return EventDefinition.objects.create(team=self.team, name="event")
+
+ def _tagger(self, kind: str) -> Callable[[Tag], TaggedItem]:
+ if kind == "action":
+ # The action model stays inside its product, so the row is written by content type and id.
+ action = create_action(team=self.team, name="action")
+ content_type_id = content_type_id_for_legacy_field("action")
+ return lambda tag: TaggedItem.objects.create(tag=tag, content_type_id=content_type_id, object_id=action.id)
+ obj = self._taggable(kind)
+ return lambda tag: obj.tagged_items.create(tag=tag)
def test_exactly_one_object_constraint(self):
dashboard = Dashboard.objects.create(team_id=self.team.id, name="private dashboard")
@@ -75,11 +85,11 @@ class TestTaggedItem(BaseTest):
@parameterized.expand(["dashboard", "insight", "event_definition", "action"])
def test_uniqueness_constraint(self, kind: str):
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- obj = self._taggable(kind)
+ tag_object = self._tagger(kind)
- obj.tagged_items.create(tag=tag)
+ tag_object(tag)
with self.assertRaises(ValidationError):
- obj.tagged_items.create(tag=tag)
+ tag_object(tag)
def test_uniqueness_constraint_property_definition(self):
try:
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 ea052c16cee1..1c0364b8d0f8 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
@@ -23,7 +23,7 @@ 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.persons import create_person
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
@parameterized_class([{"allow_event_property_expansion": True}, {"allow_event_property_expansion": False}])
@@ -44,7 +44,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIB
team_id = self.team.pk
if properties is None:
properties = []
- action = Action.objects.create(
+ action = create_action(
team_id=team_id,
name=name,
steps_json=[
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 4d48d23f5688..bc7318a0a84d 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
@@ -59,7 +59,7 @@ from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SES
from posthog.test.persons import create_person
from posthog.test.test_utils import create_group_type_mapping_without_created_at
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from ee.clickhouse.materialized_columns.columns import get_materialized_columns, materialize
@@ -82,7 +82,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
team_id = self.team.pk
if properties is None:
properties = []
- action = Action.objects.create(
+ action = create_action(
team_id=team_id,
name=name,
steps_json=[
@@ -1022,9 +1022,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
entities_property: str,
) -> None:
# API callers can omit the entity type or send one Entity rejects; both used to 500.
- entity_id = (
- Action.objects.create(team=self.team, name="untyped action").id if source_list == "actions" else "$pageview"
- )
+ entity_id = create_action(team=self.team, name="untyped action").id if source_list == "actions" else "$pageview"
raw_entity: dict[str, Any] = {"id": entity_id}
if raw_type is not None:
raw_entity["type"] = raw_type
@@ -1048,7 +1046,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
# filter and an unknown id escaped as an uncaught Action.DoesNotExist.
if action_exists:
other_team = Team.objects.create(organization=self.organization)
- action_id = Action.objects.create(team=other_team, name="other project action").id
+ action_id = create_action(team=other_team, name="other project action").id
else:
action_id = 0
@@ -1076,7 +1074,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
def test_action_filter_in_the_same_project_is_accepted(self) -> None:
sibling_environment = Team.objects.create(organization=self.organization, project=self.team.project)
- action = Action.objects.create(team=sibling_environment, name="sibling environment action")
+ action = create_action(team=sibling_environment, name="sibling environment action")
sub_query = ReplayFiltersEventsSubQuery(
team=self.team, query=RecordingsQuery(actions=[{"id": action.id, "type": "actions"}])
diff --git a/posthog/session_recordings/queries/utils.py b/posthog/session_recordings/queries/utils.py
index 45982b2bbd4b..b7bcc4dc0131 100644
--- a/posthog/session_recordings/queries/utils.py
+++ b/posthog/session_recordings/queries/utils.py
@@ -29,7 +29,8 @@ from posthog.hogql_queries.legacy_compatibility.clean_properties import clean_en
from posthog.models import Team
from posthog.types import AnyPropertyFilter
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
logger = structlog.get_logger(__name__)
@@ -243,8 +244,8 @@ def _entity_to_expr(entity: EventsNode | ActionsNode, team: Team) -> ast.Expr:
if entity.kind == "ActionsNode":
# Scoped to the project, not the team, because environments in a project share actions.
try:
- action = Action.objects.get(pk=entity.id, team__project_id=team.project_id)
- except Action.DoesNotExist:
+ action = get_action(action_id=entity.id, project_id=team.project_id)
+ except ActionNotFound:
raise ValidationError(f"Action ID {entity.id} does not exist!")
return action_to_expr(action)
else:
diff --git a/posthog/temporal/ai/sync_vectors.py b/posthog/temporal/ai/sync_vectors.py
index 33946ad3addc..2df870d0f4b8 100644
--- a/posthog/temporal/ai/sync_vectors.py
+++ b/posthog/temporal/ai/sync_vectors.py
@@ -1,12 +1,11 @@
import json
import asyncio
+import dataclasses
from collections.abc import Coroutine
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, cast
-from django.db.models import F, Q
-
import structlog
import posthoganalytics
import temporalio.common
@@ -23,7 +22,7 @@ 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 products.actions.backend.facade import api as actions_facade
from ee.hogai.summarizers.chains import abatch_summarize_actions
from ee.hogai.utils.embeddings import aembed_documents, get_async_azure_embeddings_client
@@ -31,31 +30,6 @@ from ee.hogai.utils.embeddings import aembed_documents, get_async_azure_embeddin
logger = structlog.get_logger(__name__)
-async def get_actions_qs(start_dt: datetime, offset: int | None = None, batch_size: int | None = None):
- filter_conditions = Q(
- # Only orgs that have accepted data processing
- team__organization__is_ai_data_processing_approved=True,
- # Only actions updated before the start date
- updated_at__lte=start_dt,
- ) & (
- # Never summarized actions but not deleted
- Q(last_summarized_at__isnull=True, deleted=False)
- # Actions updated after last summarization workflow
- | Q(updated_at__gte=F("last_summarized_at"))
- # The line below preserves the execution order of the workflow. Temporal workflows must be deterministic,
- # so activities can be executed in the same order in case of retries. If this line was removed, the execution
- # order with list slices would be non-deterministic, as the queryset would remove already processed actions.
- | Q(last_summarized_at=start_dt)
- )
-
- actions_to_summarize = Action.objects.filter(filter_conditions).order_by("id", "team_id", "updated_at")
- if offset is None and batch_size is None:
- return actions_to_summarize
- if offset is None or batch_size is None:
- raise ValueError("Cannot provide only offset or only batch_size")
- return actions_to_summarize[offset : offset + batch_size]
-
-
@dataclass
class GetApproximateActionsCountInputs:
start_dt: str
@@ -67,8 +41,7 @@ async def get_approximate_actions_count(inputs: GetApproximateActionsCountInputs
Retrieves the approximate count of actions to summarize. The action count can change
during the sync (updated_at > start_dt). The count is needed for batch summarization.
"""
- qs = await get_actions_qs(datetime.fromisoformat(inputs.start_dt))
- return await qs.acount()
+ return await actions_facade.acount_actions_to_summarize(start_dt=datetime.fromisoformat(inputs.start_dt))
@dataclass
@@ -87,8 +60,9 @@ async def batch_summarize_actions(inputs: BatchSummarizeActionsInputs):
inputs: Inputs for the activity.
"""
workflow_start_dt = datetime.fromisoformat(inputs.start_dt)
- actions_to_summarize = await get_actions_qs(workflow_start_dt, inputs.offset, inputs.batch_size)
- actions = [action async for action in actions_to_summarize]
+ actions = await actions_facade.alist_actions_to_summarize(
+ start_dt=workflow_start_dt, offset=inputs.offset, batch_size=inputs.batch_size
+ )
logger.info(
"Preparing to summarize actions",
@@ -103,7 +77,7 @@ async def batch_summarize_actions(inputs: BatchSummarizeActionsInputs):
start_dt=inputs.start_dt,
properties={"offset": inputs.offset, "batch_size": inputs.batch_size, "start_dt": inputs.start_dt},
)
- models_to_update = []
+ new_summaries: dict[int, str] = {}
for action, maybe_summary in zip(actions, summaries):
# If a few actions across the batch fail, we don't want to fail the entire workflow.
if isinstance(maybe_summary, BaseException):
@@ -115,11 +89,9 @@ async def batch_summarize_actions(inputs: BatchSummarizeActionsInputs):
capture_exception(maybe_summary, additional_properties={"action_id": action.id, "tag": "max_ai"})
logger.exception("Error summarizing actions", error=maybe_summary, action_id=action.id)
continue
- action.last_summarized_at = workflow_start_dt
- action.summary = maybe_summary
- models_to_update.append(action)
+ new_summaries[action.id] = maybe_summary
- await Action.objects.abulk_update(models_to_update, ["last_summarized_at", "summary"])
+ await actions_facade.asave_action_summaries(summaries=new_summaries, summarized_at=workflow_start_dt)
async def batch_embed_actions(
@@ -216,20 +188,10 @@ async def sync_action_vectors(
await client.execute_query(INSERT_BULK_PG_EMBEDDINGS_SQL, *rows)
- bulk_update = []
- for action, _ in batch:
- action_model = Action(id=action["id"], embedding_last_synced_at=workflow_start_dt)
- if embedding_version is not None:
- action_model.embedding_version = embedding_version
- bulk_update.append(action_model)
-
- await Action.objects.abulk_update(
- bulk_update,
- (
- ["embedding_last_synced_at", "embedding_version"]
- if embedding_version is not None
- else ["embedding_last_synced_at"]
- ),
+ await actions_facade.amark_actions_embedded(
+ action_ids=[action["id"] for action, _ in batch],
+ synced_at=workflow_start_dt,
+ embedding_version=embedding_version,
)
@@ -261,37 +223,6 @@ async def batch_embed_and_sync_actions(inputs: BatchEmbedAndSyncActionsInputs) -
tag_queries(product=Product.MAX_AI)
workflow_start_dt = datetime.fromisoformat(inputs.start_dt)
- query = (
- # Include only updated actions.
- Q(last_summarized_at__gt=F("embedding_last_synced_at"))
- # Or actions that haven't never been synced but have summaries.
- | (Q(embedding_last_synced_at__isnull=True) & Q(last_summarized_at__isnull=False))
- )
-
- # Backward compatibility: Temporal workflows must be deterministic, so we won't
- # look for embedding versions if the version is not set in the inputs.
- if inputs.embedding_version is not None:
- query |= (
- # Or actions that don't have an embedding version.
- Q(embedding_version__isnull=True)
- # Or actions with an old embedding version.
- | Q(embedding_version__lt=inputs.embedding_version)
- )
-
- actions_to_sync_qs = (
- Action.objects.filter(
- Q(
- # Include only actions that have been summarized.
- last_summarized_at__lte=workflow_start_dt,
- # And they must have a summary to prevent infinite loops.
- summary__isnull=False,
- )
- & query
- )
- .order_by("updated_at", "id")
- .values("team_id", "id", "summary", "name", "description", "deleted")
- )
-
actions_batch_size = inputs.embeddings_batch_size * inputs.max_parallel_requests
offset = 0
embedded_actions: list[tuple[dict[str, Any], list[float]]] = []
@@ -300,7 +231,13 @@ async def batch_embed_and_sync_actions(inputs: BatchEmbedAndSyncActionsInputs) -
temporalio.activity.heartbeat()
qs_slice = [
- cast(dict[str, Any], action) async for action in actions_to_sync_qs[offset : offset + actions_batch_size]
+ dataclasses.asdict(action)
+ for action in await actions_facade.alist_actions_to_embed(
+ start_dt=workflow_start_dt,
+ embedding_version=inputs.embedding_version,
+ offset=offset,
+ limit=actions_batch_size,
+ )
]
if not qs_slice:
break
diff --git a/posthog/temporal/tests/ai/test_sync_vectors.py b/posthog/temporal/tests/ai/test_sync_vectors.py
index dad9a0ed3f73..48cb04ec18ea 100644
--- a/posthog/temporal/tests/ai/test_sync_vectors.py
+++ b/posthog/temporal/tests/ai/test_sync_vectors.py
@@ -11,6 +11,7 @@ from django.conf import settings
from django.utils import timezone
import pytest_asyncio
+from asgiref.sync import sync_to_async
from azure.ai.inference.aio import EmbeddingsClient
from azure.ai.inference.models import EmbeddingItem, EmbeddingsResult, EmbeddingsUsage
from azure.core.credentials import AzureKeyCredential
@@ -34,13 +35,13 @@ from posthog.temporal.ai.sync_vectors import (
batch_embed_actions,
batch_embed_and_sync_actions,
batch_summarize_actions,
- get_actions_qs,
get_approximate_actions_count,
sync_action_vectors,
)
from posthog.temporal.common.clickhouse import get_client
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import acreate_action, aget_action_ai_state, delete_action
@pytest.fixture(autouse=True)
@@ -53,48 +54,55 @@ def cleanup():
pass
-def action_models(ateam):
- return (
- Action(
- team=ateam,
- name="Completed onboarding",
- description="Filters users who successfully completed onboarding",
- steps_json=[{"event": "onboarding completed"}],
- ),
- Action(
- team=ateam,
- name="Requested a quote",
- description="Display users who wanted to purchase the product",
- steps_json=[{"href": "/subscribe", "href_matching": "exact", "event": "pressed button"}],
- ),
- Action(
- team=ateam,
- name="Interacted with the assistant",
- description="Cohort of events when users interacted with the AI assistant",
- steps_json=[{"event": "message sent"}, {"url": "/chat", "event": "$pageview"}],
- ),
- )
+ACTION_FIELDS: tuple[dict[str, Any], ...] = (
+ {
+ "name": "Completed onboarding",
+ "description": "Filters users who successfully completed onboarding",
+ "steps_json": [{"event": "onboarding completed"}],
+ },
+ {
+ "name": "Requested a quote",
+ "description": "Display users who wanted to purchase the product",
+ "steps_json": [{"href": "/subscribe", "href_matching": "exact", "event": "pressed button"}],
+ },
+ {
+ "name": "Interacted with the assistant",
+ "description": "Cohort of events when users interacted with the AI assistant",
+ "steps_json": [{"event": "message sent"}, {"url": "/chat", "event": "$pageview"}],
+ },
+)
+
+
+async def _plant_actions(team, fields: list[dict[str, Any]]) -> list[Action]:
+ # One at a time, so ids ascend in the order given.
+ return [await acreate_action(team=team, **action_fields) for action_fields in fields]
+
+
+async def _remove_actions(actions: list[Action]) -> None:
+ for action in actions:
+ await sync_to_async(delete_action)(action)
@pytest_asyncio.fixture
-async def actions(action_models, ateam):
- await Action.objects.abulk_create(action_models)
- yield action_models
- await Action.objects.filter(team=ateam).adelete()
+async def actions(ateam):
+ planted = await _plant_actions(ateam, list(ACTION_FIELDS))
+ yield planted
+ await _remove_actions(planted)
@pytest_asyncio.fixture
-async def summarized_actions(action_models, ateam):
+async def summarized_actions(ateam):
dt = timezone.now()
summaries = ["Test summary 1", "Test summary 2", "Test summary 3"]
- for action, summary in zip(action_models, summaries):
- action.last_summarized_at = dt
- action.summary = summary
-
- await Action.objects.abulk_create(action_models)
- yield action_models
- await Action.objects.filter(team=ateam).adelete()
+ planted = await _plant_actions(
+ ateam,
+ [
+ {**action_fields, "last_summarized_at": dt, "summary": summary}
+ for action_fields, summary in zip(ACTION_FIELDS, summaries)
+ ],
+ )
+ yield planted
+ await _remove_actions(planted)
@pytest.fixture
@@ -140,60 +148,6 @@ def _query_pg_embeddings() -> list[tuple]:
return sync_execute("SELECT * FROM pg_embeddings ORDER BY id")
-async def test_get_actions_qs(actions):
- qs = await get_actions_qs(timezone.now())
- assert await qs.acount() == 3
- qs = await get_actions_qs(timezone.now(), 0, 1)
- assert await qs.acount() == 1
- qs = await get_actions_qs(timezone.now() - timedelta(days=1))
- assert await qs.acount() == 0
-
- dt = timezone.now()
- action = actions[0]
- action.last_summarized_at = dt + timedelta(seconds=1)
- await action.asave()
-
- qs = await get_actions_qs(dt + timedelta(seconds=2))
- assert await qs.acount() == 2
-
-
-async def test_get_actions_qs_with_deleted_actions(actions):
- start_dt = timezone.now()
-
- # Never summarized and deleted
- action_1, action_2, action_3 = actions
- action_1.deleted = True
- await action_1.asave()
-
- # Updated after last summarization
- action_2.updated_at = start_dt - timedelta(hours=1)
- action_2.last_summarized_at = start_dt - timedelta(hours=2)
- await action_2.asave()
-
- # Deleted but updated after last summarization
- action_3.updated_at = start_dt - timedelta(hours=2)
- action_3.last_summarized_at = start_dt - timedelta(hours=1)
- action_3.deleted = True
- await action_3.asave()
-
- qs = await get_actions_qs(start_dt + timedelta(hours=1))
- assert await qs.acount() == 2
- assert {a async for a in qs.values_list("id", flat=True)} == {action_2.id, action_3.id}
-
-
-async def test_get_actions_qs_with_unapproved_organization(aorganization):
- aorganization.is_ai_data_processing_approved = False
- await aorganization.asave()
- qs = await get_actions_qs(timezone.now())
- assert await qs.acount() == 0
-
-
@pytest.mark.django_db
@pytest.mark.asyncio
async def test_get_approximate_actions_count(actions):
@@ -215,17 +169,16 @@ async def test_basic_batch_summarization(azure_mock, actions):
)
assert summarize_mock.call_count == 1
- updated_action = actions[0]
- await updated_action.arefresh_from_db()
- assert updated_action.summary == "Test1"
- assert updated_action.last_summarized_at == start_dt
- assert updated_action.embedding_last_synced_at is None
+ updated_state = await aget_action_ai_state(actions[0])
+ assert updated_state.summary == "Test1"
+ assert updated_state.last_summarized_at == start_dt
+ assert updated_state.embedding_last_synced_at is None
for action in actions[1:]:
- await action.arefresh_from_db()
- assert action.summary is None
- assert action.last_summarized_at is None
- assert action.embedding_last_synced_at is None
+ state = await aget_action_ai_state(action)
+ assert state.summary is None
+ assert state.last_summarized_at is None
+ assert state.embedding_last_synced_at is None
summarize_mock.return_value = ["Test2", "Test3"]
@@ -236,15 +189,15 @@ async def test_basic_batch_summarization(azure_mock, actions):
expected_texts = ["Test1", "Test2", "Test3"]
for action, expected_text in zip(actions, expected_texts):
- await action.arefresh_from_db()
- assert action.summary == expected_text
- assert action.last_summarized_at == start_dt
- assert action.embedding_last_synced_at is None
+ state = await aget_action_ai_state(action)
+ assert state.summary == expected_text
+ assert state.last_summarized_at == start_dt
+ assert state.embedding_last_synced_at is None
@pytest.mark.django_db
@pytest.mark.asyncio
-async def test_batch_summarize_with_errors(azure_mock, actions: tuple[Action], ateam):
+async def test_batch_summarize_with_errors(azure_mock, actions: list[Action], ateam):
with (
patch("posthog.temporal.ai.sync_vectors.abatch_summarize_actions") as summarize_mock,
):
@@ -254,7 +207,7 @@ async def test_batch_summarize_with_errors(azure_mock, actions: tuple[Action], a
await batch_summarize_actions(
BatchSummarizeActionsInputs(offset=0, batch_size=96, start_dt=start_dt.isoformat())
)
- updated_actions = [action async for action in Action.objects.filter(team=ateam).order_by("id")]
+ updated_actions = [await aget_action_ai_state(action) for action in actions]
assert len(updated_actions) == 3
assert updated_actions[0].summary == "Test1"
assert updated_actions[1].summary == "Test2"
@@ -279,7 +232,7 @@ async def test_batch_summarize_with_errors(azure_mock, actions: tuple[Action], a
assert summarize_mock.call_count == 1
assert len(summarize_mock.call_args[0][0]) == 1
- updated_actions = [action async for action in Action.objects.filter(team=ateam).order_by("id")]
+ updated_actions = [await aget_action_ai_state(action) for action in actions]
assert len(updated_actions) == 3
assert ("Test1", "Test2", "Test3") == tuple(action.summary for action in updated_actions)
assert [start_dt, start_dt, new_start_dt] == [action.last_summarized_at for action in updated_actions]
@@ -325,7 +278,7 @@ async def test_batch_embedding(azure_mock, actions):
@pytest.mark.django_db
@pytest.mark.asyncio
-async def test_batch_embedding_with_errors(azure_mock, actions: tuple[Action]):
+async def test_batch_embedding_with_errors(azure_mock, actions: list[Action]):
with patch("azure.ai.inference.aio.EmbeddingsClient.embed") as embeddings_mock:
# batch_size=1, one call
embeddings_mock.side_effect = ValueError("Test error")
@@ -403,8 +356,7 @@ async def test_clickhouse_sync_single_batch(summarized_actions, summarized_actio
assert expected_result == parse_records(embeddings)
for action in summarized_actions:
- await action.arefresh_from_db()
- assert action.embedding_last_synced_at == start_dt
+ assert (await aget_action_ai_state(action)).embedding_last_synced_at == start_dt
with patch("posthog.temporal.common.clickhouse.ClickHouseClient.execute_query") as mock:
await sync_action_vectors(client, summarized_actions_with_embeddings, 10, start_dt)
@@ -436,8 +388,7 @@ async def test_clickhouse_sync_multiple_batches(summarized_actions, summarized_a
assert expected_result == parse_records(embeddings)
for action in summarized_actions:
- await action.arefresh_from_db()
- assert action.embedding_last_synced_at == start_dt
+ assert (await aget_action_ai_state(action)).embedding_last_synced_at == start_dt
with patch("posthog.temporal.common.clickhouse.ClickHouseClient.execute_query") as mock:
await sync_action_vectors(client, summarized_actions_with_embeddings, 1, start_dt)
@@ -567,23 +518,28 @@ async def test_batch_embed_and_sync_actions_filters_out_actions(azure_mock, atea
embeddings = [[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]]
# Create actions with different last_summarized_at values
- actions = [
- Action(
- team=ateam, name="Before start 1", last_summarized_at=start_dt - timedelta(days=1), summary="Test1"
- ), # Should be included
- Action(
- team=ateam,
- name="Before start 2",
- last_summarized_at=start_dt - timedelta(days=1),
- embedding_last_synced_at=start_dt - timedelta(days=2),
- summary="Test2",
- ), # Should be included
- Action(team=ateam, name="At start", last_summarized_at=start_dt, summary="Test3"), # Should be included
- Action(
- team=ateam, name="After start", last_summarized_at=start_dt + timedelta(days=1), summary="Test4"
- ), # Should not be included
- ]
- await Action.objects.abulk_create(actions)
+ actions = await _plant_actions(
+ ateam,
+ [
+ {
+ "name": "Before start 1",
+ "last_summarized_at": start_dt - timedelta(days=1),
+ "summary": "Test1",
+ }, # Should be included
+ {
+ "name": "Before start 2",
+ "last_summarized_at": start_dt - timedelta(days=1),
+ "embedding_last_synced_at": start_dt - timedelta(days=2),
+ "summary": "Test2",
+ }, # Should be included
+ {"name": "At start", "last_summarized_at": start_dt, "summary": "Test3"}, # Should be included
+ {
+ "name": "After start",
+ "last_summarized_at": start_dt + timedelta(days=1),
+ "summary": "Test4",
+ }, # Should not be included
+ ],
+ )
with (
patch("azure.ai.inference.aio.EmbeddingsClient.embed") as embeddings_mock,
@@ -615,12 +571,9 @@ async def test_batch_embed_and_sync_actions_filters_out_actions_with_no_summary(
start_dt = timezone.now()
# Create actions with different last_summarized_at values
- actions = [
- Action(
- team=ateam, name="Before start 1", last_summarized_at=start_dt - timedelta(days=1)
- ), # Should be included
- ]
- await Action.objects.abulk_create(actions)
+ await _plant_actions(
+ ateam, [{"name": "Before start 1", "last_summarized_at": start_dt - timedelta(days=1)}]
+ ) # Has no summary, so it is never embedded
with patch("temporalio.activity.heartbeat"):
result = await batch_embed_and_sync_actions(
@@ -636,36 +589,34 @@ async def test_batch_embed_and_sync_actions_filters_out_actions_with_no_summary(
assert len(rows) == 0
-async def _create_actions_with_embedding_version(ateam, start_dt):
+async def _create_actions_with_embedding_version(ateam, start_dt) -> list[Action]:
# Create actions with different last_summarized_at values
- actions = [
- Action(
- team=ateam,
- name="Before start 1",
- last_summarized_at=start_dt - timedelta(days=1),
- embedding_last_synced_at=start_dt - timedelta(hours=8), # shouldn't be included by time filters
- summary="Test1",
- embedding_version=None,
- ), # Should be included
- Action(
- team=ateam,
- name="Before start 2",
- last_summarized_at=start_dt - timedelta(days=1),
- embedding_last_synced_at=start_dt - timedelta(hours=8), # shouldn't be included by time filters
- summary="Test2",
- embedding_version=1,
- ), # Should be included
- Action(
- team=ateam,
- name="Before start 2",
- last_summarized_at=start_dt - timedelta(days=1),
- embedding_last_synced_at=start_dt - timedelta(days=2),
- summary="Test2",
- embedding_version=2, # Should not be included by the version filter
- ), # Should be included
- ]
- await Action.objects.abulk_create(actions)
- return actions
+ return await _plant_actions(
+ ateam,
+ [
+ {
+ "name": "Before start 1",
+ "last_summarized_at": start_dt - timedelta(days=1),
+ "embedding_last_synced_at": start_dt - timedelta(hours=8), # shouldn't be included by time filters
+ "summary": "Test1",
+ "embedding_version": None,
+ }, # Should be included
+ {
+ "name": "Before start 2",
+ "last_summarized_at": start_dt - timedelta(days=1),
+ "embedding_last_synced_at": start_dt - timedelta(hours=8), # shouldn't be included by time filters
+ "summary": "Test2",
+ "embedding_version": 1,
+ }, # Should be included
+ {
+ "name": "Before start 2",
+ "last_summarized_at": start_dt - timedelta(days=1),
+ "embedding_last_synced_at": start_dt - timedelta(days=2),
+ "summary": "Test2",
+ "embedding_version": 2, # Should not be included by the version filter
+ }, # Should be included
+ ],
+ )
@pytest.mark.django_db
@@ -705,8 +656,7 @@ async def test_batch_embed_and_sync_actions_embedding_version(azure_mock, ateam)
} == {2}
for action in actions:
- await action.arefresh_from_db()
- assert action.embedding_version == 2
+ assert (await aget_action_ai_state(action)).embedding_version == 2
@pytest.mark.asyncio
@@ -895,8 +845,7 @@ async def test_updates_embedding_version(embeddings_mock, azure_mock, ateam):
}
for action in actions:
- await action.arefresh_from_db()
- assert action.embedding_version == 2
+ assert (await aget_action_ai_state(action)).embedding_version == 2
@pytest.mark.asyncio
@@ -1032,19 +981,19 @@ async def test_heartbeat_called_multiple_times_with_large_batch(azure_mock, atea
start_dt = timezone.now()
# Create more actions to process multiple iterations
- actions = []
- for i in range(10):
- actions.append(
- Action(
- team=ateam,
- name=f"Action {i}",
- description=f"Description {i}",
- last_summarized_at=start_dt - timedelta(days=1),
- summary=f"Summary {i}",
- steps_json=[{"event": f"event_{i}"}],
- )
- )
- await Action.objects.abulk_create(actions)
+ await _plant_actions(
+ ateam,
+ [
+ {
+ "name": f"Action {i}",
+ "description": f"Description {i}",
+ "last_summarized_at": start_dt - timedelta(days=1),
+ "summary": f"Summary {i}",
+ "steps_json": [{"event": f"event_{i}"}],
+ }
+ for i in range(10)
+ ],
+ )
embeddings = [[0.1, 0.1] for _ in range(10)]
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 363572bd8f71..de0215c74cf3 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -229,7 +229,7 @@ from posthog.session_recordings.sql.session_replay_event_sql import (
from posthog.test import flush_lock_guard
from posthog.test.assert_faster_than import assert_faster_than
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.sql import TRUNCATE_COHORTPEOPLE_TABLE_SQL
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
@@ -1931,8 +1931,7 @@ def _create_action(**kwargs):
team = kwargs.pop("team")
name = kwargs.pop("name")
properties = kwargs.pop("properties", {})
- action = Action.objects.create(team=team, name=name, steps_json=[{"event": name, "properties": properties}])
- return action
+ return create_action(team=team, name=name, steps_json=[{"event": name, "properties": properties}])
class ClickhouseTestMixin(QueryMatchingTest):
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index e7bf8d9d67cd..28f3c423b1ef 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -202,7 +202,6 @@ post_save:products.annotations.backend.activity_logging.annotation_created
post_save:products.authorization.backend.logic.session.invalidate
post_save:products.autoresearch.backend.signals.on_task_run_saved
post_save:products.canvas.backend.search_sync.canvas_saved
-post_save:products.cdp.backend.models.hog_functions.hog_function.action_saved
post_save:products.cdp.backend.models.hog_functions.hog_function.cohort_saved
post_save:products.cdp.backend.models.hog_functions.hog_function.enabled_default_hog_functions_for_new_team
post_save:products.cdp.backend.models.hog_functions.hog_function.hog_function_saved
@@ -286,7 +285,6 @@ post_save:products.tasks.backend.search_index.channel_saved
post_save:products.tasks.backend.search_index.task_artifact_saved
post_save:products.tasks.backend.search_index.task_run_saved
post_save:products.tasks.backend.search_index.task_saved
-post_save:products.workflows.backend.models.hog_flow.hog_flow.action_saved_for_hog_flows
post_save:products.workflows.backend.models.hog_flow.hog_flow.hog_flow_saved
post_save:products.workflows.backend.models.hog_flow.hog_flow.team_saved_for_hog_flows
post_save:products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.handle_hog_flow_batch_job_created
diff --git a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
index 02436a23777a..b6f9525417ff 100644
--- a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
+++ b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
@@ -92,8 +92,8 @@ REVIEWED_WRITABLE: dict[str, str] = {
"posthog.api.my_notifications.MyNotificationsSerializer.created_at": "TODO: server-owned activity log timestamp, make read-only",
"posthog.session_recordings.session_recording_api.SessionRecordingSharedSerializer.end_time": "TODO: server-owned, derived from the ingested replay events",
"posthog.session_recordings.session_recording_api.SessionRecordingSharedSerializer.start_time": "TODO: server-owned, derived from the ingested replay events",
- "products.actions.backend.api.action.ActionSerializer.last_calculated_at": "TODO: server-owned, written by the action calculation job",
- "products.actions.backend.api.action.ActionSerializer.pinned_at": "TODO: server-derived on pin. update() discards the supplied value and stores its own now(); only the null that unpins is the client's",
+ "products.actions.backend.presentation.views.action.ActionSerializer.last_calculated_at": "TODO: server-owned, written by the action calculation job",
+ "products.actions.backend.presentation.views.action.ActionSerializer.pinned_at": "TODO: server-derived on pin. update() discards the supplied value and stores its own now(); only the null that unpins is the client's",
"products.alerts.backend.presentation.views.alert.AlertSerializer.snoozed_until": "TODO: server-derived. The client sends a relative date string and update() resolves it to the stored instant",
"products.annotations.backend.api.annotation.AnnotationSerializer.date_marker": "Client sets when the annotation happened, to place it on a chart",
"products.billing_alerts.backend.presentation.serializers.BillingAlertConfigurationSerializer.snoozed_until": "Client-set instant: a plain DateTimeField that ModelSerializer writes to the column unchanged, with no relative-duration parsing on this path",
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 28b86e8b948b..e73b7ca1115e 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -56,7 +56,7 @@ from posthog.utils import get_ip_address, get_trusted_client_ip
from products.access_control.backend.models.access_control import AccessControl
from products.access_control.backend.models.role import Role, RoleMembership
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -626,7 +626,7 @@ class TestAutoProjectMiddleware(APIBaseTest):
self.assertEqual(response_insights_api.status_code, 200)
def test_project_switched_when_accessing_action_of_another_accessible_team(self):
- action = Action.objects.create(team=self.second_team)
+ action = create_action(team=self.second_team)
response_app = self.client.get(f"/action/{action.id}")
response_users_api = self.client.get(f"/api/users/@me/")
diff --git a/products/access_control/backend/tests/test_access_control.py b/products/access_control/backend/tests/test_access_control.py
index 290a3a98af99..a71c91b0e3a3 100644
--- a/products/access_control/backend/tests/test_access_control.py
+++ b/products/access_control/backend/tests/test_access_control.py
@@ -226,9 +226,9 @@ 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 products.actions.backend.models.action import Action
+ from products.actions.backend.facade.testing import create_action
- action = Action.objects.create(team=self.team, name="test action")
+ action = create_action(team=self.team, name="test action")
res = self.client.put(
f"/api/projects/@current/actions/{action.id}/access_controls",
@@ -240,9 +240,9 @@ 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 products.actions.backend.models.action import Action
+ from products.actions.backend.facade.testing import create_action
- action = Action.objects.create(team=self.team, name="test action")
+ action = create_action(team=self.team, name="test action")
for level in ["viewer", "editor", "manager"]:
res = self.client.put(
diff --git a/products/actions/backend/apps.py b/products/actions/backend/apps.py
index f800027844b8..747b1da79b1f 100644
--- a/products/actions/backend/apps.py
+++ b/products/actions/backend/apps.py
@@ -10,4 +10,13 @@ class ActionsConfig(AppConfig):
# Connect the action activity-log receiver at app-population, from a dedicated light
# module. It must not live in the viewset module: that pulls posthog.api routing/utils
# (and posthog.schema with them) into django.setup() for every process type.
+ from posthog.models.file_system.unfiled_file_saver import register_mixin_model # noqa: PLC0415
+ from posthog.models.resource_transfer.registered_models import register_model # noqa: PLC0415
+
from products.actions.backend import activity_logging # noqa: F401, PLC0415
+ from products.actions.backend.models.action import Action # noqa: PLC0415
+
+ # Core keeps per-model registries for unfiled items and resource transfer. Registering from here
+ # keeps those modules from importing this product's model.
+ register_mixin_model("action", Action)
+ register_model("Action", Action)
diff --git a/products/actions/backend/facade/api.py b/products/actions/backend/facade/api.py
index 0b0ab8cc4758..2aa236b6d29a 100644
--- a/products/actions/backend/facade/api.py
+++ b/products/actions/backend/facade/api.py
@@ -12,14 +12,276 @@ Do NOT:
from __future__ import annotations
-from collections.abc import Sequence
+from collections.abc import Callable, Collection, Iterable, Mapping, Sequence
+from datetime import datetime
+from typing import TYPE_CHECKING, Any
-from posthog.hogql import ast
-from posthog.hogql.property import action_to_expr
+from django.db import router
-from posthog.models import Team
+import structlog
-from products.actions.backend.models.action import Action
+from posthog.exceptions_capture import capture_exception
+
+from products.actions.backend.facade import contracts
+from products.actions.backend.logic import (
+ actions as logic,
+ saved_handlers,
+)
+from products.actions.backend.models.action import Action as ActionModel
+
+if TYPE_CHECKING:
+ from posthog.hogql import ast
+
+ from posthog.models import Team, User
+
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+logger = structlog.get_logger(__name__)
+
+__all__ = [
+ "acount_actions_to_summarize",
+ "action_filter_conditions",
+ "action_read_db_alias",
+ "aget_action",
+ "alist_actions",
+ "alist_actions_to_embed",
+ "alist_actions_to_summarize",
+ "amark_actions_embedded",
+ "asave_action_summaries",
+ "accessible_action_ids",
+ "create_action",
+ "existing_action_ids",
+ "find_actions_by_name",
+ "find_action_team_id",
+ "get_action",
+ "get_action_inventory",
+ "get_action_names",
+ "get_actions",
+ "list_action_catalog",
+ "list_actions",
+ "list_top_actions",
+ "on_action_saved",
+ "readable_action_ids",
+ "search_actions",
+]
+
+
+def _to_contract(action: ActionModel) -> contracts.Action:
+ return contracts.Action(
+ id=action.id,
+ team_id=action.team_id,
+ name=action.name,
+ description=action.description,
+ steps=tuple(action.steps),
+ deleted=action.deleted,
+ created_by_id=action.created_by_id,
+ created_at=action.created_at,
+ updated_at=action.updated_at,
+ pinned_at=action.pinned_at,
+ last_calculated_at=action.last_calculated_at,
+ summary=action.summary,
+ )
+
+
+# Reads
+
+
+def get_action(
+ *,
+ action_id: int,
+ project_id: int | None = None,
+ team_id: int | None = None,
+ include_deleted: bool = True,
+) -> contracts.Action:
+ """One action, scoped to a project or to a team. Raises `ActionNotFound` outside that scope.
+
+ Actions live on the project's root team, so a child environment finds them by `project_id`.
+ `team_id` matches the owning team exactly. A deleted action is returned unless `include_deleted=False`,
+ because a saved query keeps naming an action after it is deleted.
+ """
+ queryset = logic.live_or_all(logic.scoped(project_id=project_id, team_id=team_id), include_deleted=include_deleted)
+ try:
+ return _to_contract(queryset.get(pk=action_id))
+ except ActionModel.DoesNotExist:
+ raise contracts.ActionNotFound(f"Action {action_id} does not exist") from None
+
+
+async def aget_action(
+ *,
+ action_id: int,
+ project_id: int | None = None,
+ team_id: int | None = None,
+ include_deleted: bool = True,
+) -> contracts.Action:
+ queryset = logic.live_or_all(logic.scoped(project_id=project_id, team_id=team_id), include_deleted=include_deleted)
+ try:
+ return _to_contract(await queryset.aget(pk=action_id))
+ except ActionModel.DoesNotExist:
+ raise contracts.ActionNotFound(f"Action {action_id} does not exist") from None
+
+
+def get_actions(
+ *,
+ action_ids: Iterable[int],
+ project_id: int | None = None,
+ team_id: int | None = None,
+ include_deleted: bool = True,
+) -> list[contracts.Action]:
+ """The actions among `action_ids` that exist in the scope. A missing id is left out, not an error."""
+ queryset = logic.live_or_all(logic.scoped(project_id=project_id, team_id=team_id), include_deleted=include_deleted)
+ return [_to_contract(action) for action in queryset.filter(pk__in=list(action_ids))]
+
+
+def list_actions(
+ *, project_id: int | None = None, team_id: int | None = None, include_deleted: bool = False
+) -> list[contracts.Action]:
+ """Every action in the scope, live ones only unless `include_deleted`."""
+ queryset = logic.live_or_all(logic.scoped(project_id=project_id, team_id=team_id), include_deleted=include_deleted)
+ return [_to_contract(action) for action in queryset]
+
+
+async def alist_actions(
+ *, project_id: int | None = None, team_id: int | None = None, include_deleted: bool = False
+) -> list[contracts.Action]:
+ queryset = logic.live_or_all(logic.scoped(project_id=project_id, team_id=team_id), include_deleted=include_deleted)
+ return [_to_contract(action) async for action in queryset]
+
+
+def list_top_actions(*, project_id: int, limit: int) -> list[contracts.Action]:
+ """Up to `limit` live actions, pinned ones first and then the most recently calculated."""
+ return [_to_contract(action) for action in logic.top_actions(project_id=project_id, limit=limit)]
+
+
+def get_action_names(*, project_id: int, action_ids: Iterable[int]) -> dict[int, str | None]:
+ """Name by id for the actions among `action_ids` in the project, deleted ones included."""
+ return dict(
+ logic.scoped(project_id=project_id, team_id=None).filter(pk__in=list(action_ids)).values_list("pk", "name")
+ )
+
+
+def existing_action_ids(*, project_id: int, action_ids: Iterable[int]) -> list[int]:
+ """The ids among `action_ids` that name an action in the project, deleted ones included."""
+ return list(
+ logic.scoped(project_id=project_id, team_id=None).filter(pk__in=list(action_ids)).values_list("pk", flat=True)
+ )
+
+
+def find_action_team_id(*, action_id: int, include_deleted: bool = True) -> int | None:
+ """The team that owns an action, or None when it does not exist.
+
+ Unscoped: only for a caller that got the id from a trusted source, such as a save signal, or
+ that checks the user's access to the returned team itself.
+ """
+ return logic.team_id_of(action_id=action_id, include_deleted=include_deleted)
+
+
+def find_actions_by_name(
+ *, name: str, project_id: int | None = None, team_id: int | None = None, include_deleted: bool = False
+) -> list[contracts.Action]:
+ """The actions in the scope with exactly this name, oldest first. Names are not unique."""
+ queryset = logic.live_or_all(
+ logic.scoped(project_id=project_id, team_id=team_id), include_deleted=include_deleted
+ ).filter(name=name)
+ return [_to_contract(action) for action in queryset.order_by("pk")]
+
+
+def get_action_inventory(*, team_id: int, recent_limit: int) -> contracts.ActionInventory:
+ """How many live actions the team has, and the `recent_limit` it changed most recently."""
+ queryset = logic.scoped(project_id=None, team_id=team_id).filter(deleted=False)
+ total = queryset.count()
+ recent = queryset.order_by("-updated_at")[:recent_limit].values("id", "name", "updated_at")
+ return contracts.ActionInventory(
+ total_count=total,
+ recent=tuple(
+ contracts.ActionRecentEntry(id=row["id"], name=row["name"], updated_at=row["updated_at"]) for row in recent
+ ),
+ )
+
+
+# Reads that apply a user's access
+
+
+def readable_action_ids(
+ *,
+ project_id: int,
+ action_ids: Collection[int],
+ access_control: UserAccessControl,
+ required_level: Any = "viewer",
+) -> set[int]:
+ """The ids among `action_ids` that name an action in the project the user holds `required_level` on.
+
+ Each action is checked as an object, so an action from a sibling environment resolves against the
+ rules of the team `access_control` is for.
+ """
+ return logic.readable_ids(
+ project_id=project_id, action_ids=action_ids, access_control=access_control, required_level=required_level
+ )
+
+
+def accessible_action_ids(*, team_id: int, action_ids: Collection[int], access_control: UserAccessControl) -> set[int]:
+ """The ids among `action_ids` that name a live action of the team the user may list."""
+ return logic.accessible_ids(team_id=team_id, action_ids=action_ids, access_control=access_control)
+
+
+def action_read_db_alias() -> str:
+ """The database alias a catalog read of actions runs on, so a caller can bound that connection."""
+ return router.db_for_read(ActionModel)
+
+
+def list_action_catalog(
+ *, team_id: int, access_control: UserAccessControl, limit: int, using: str | None = None
+) -> list[contracts.ActionCatalogEntry]:
+ """The team's live actions the user may list, most recently updated first."""
+ return logic.catalog_entries(team_id=team_id, access_control=access_control, limit=limit, using=using)
+
+
+def search_actions(
+ *,
+ project_id: int,
+ query: str | None,
+ access_control: UserAccessControl,
+ limit: int,
+ offset: int = 0,
+ include_deleted: bool = True,
+ with_access_levels: bool = False,
+ include_count: bool = True,
+) -> tuple[list[dict[str, Any]], int]:
+ """Ranked full-text search over a project's actions, in the result shape of core search.
+
+ Without a query the actions come in name order. ``with_access_levels`` adds ``user_access_level``,
+ the user's resolved level for each action. ``include_count=False`` skips the count query and
+ reports a total of 0.
+ """
+ rows, total_count = logic.search(
+ project_id=project_id,
+ query=query,
+ access_control=access_control,
+ limit=limit,
+ offset=offset,
+ include_deleted=include_deleted,
+ include_count=include_count,
+ )
+ access_levels = (
+ access_control.bulk_object_access_levels("action", [(str(row["id"]), row["created_by_id"]) for row in rows])
+ if with_access_levels
+ else {}
+ )
+ results: list[dict[str, Any]] = []
+ for row in rows:
+ result: dict[str, Any] = {
+ "type": "action",
+ "result_id": str(row["id"]),
+ "extra_fields": {"name": row["name"], "description": row["description"]},
+ }
+ if query:
+ result["rank"] = row["rank"]
+ if with_access_levels:
+ result["user_access_level"] = access_levels.get(str(row["id"]))
+ results.append(result)
+ return results, total_count
+
+
+# HogQL
def action_filter_conditions(*, team: Team, action_ids: Sequence[int]) -> dict[int, ast.Expr]:
@@ -35,16 +297,140 @@ def action_filter_conditions(*, team: Team, action_ids: Sequence[int]) -> dict[i
when it has no steps. A stepless action compiles to a condition that matches every event, which
reads as a filter but is not one.
"""
+ from posthog.hogql.property import action_to_expr # noqa: PLC0415 — keeps HogQL off the facade's import path
+
if not action_ids:
return {}
conditions: dict[int, ast.Expr] = {}
- for action in Action.objects.filter(team__project_id=team.project_id, id__in=action_ids, deleted=False):
+ for action in ActionModel.objects.filter(team__project_id=team.project_id, id__in=action_ids, deleted=False):
if not action.steps:
continue
try:
- conditions[action.id] = action_to_expr(action)
+ conditions[action.id] = action_to_expr(_to_contract(action))
except Exception:
# One action with an uncompilable step must not cost the caller the rest of them.
continue
return conditions
+
+
+# Writes
+
+
+def create_action(
+ *,
+ team: Team,
+ name: str | None,
+ steps_json: Sequence[Mapping[str, object]] | None = None,
+ description: str = "",
+ created_by: User | None = None,
+ pinned_at: datetime | None = None,
+) -> contracts.Action:
+ """Create an action from steps in the stored JSON shape. Saving compiles its bytecode.
+
+ A child environment's team is swapped for its project's root team, where actions live.
+ """
+ return _to_contract(
+ logic.create(
+ team=team,
+ name=name,
+ steps_json=steps_json,
+ description=description,
+ created_by=created_by,
+ pinned_at=pinned_at,
+ )
+ )
+
+
+def on_action_saved(handler: Callable[[contracts.ActionSaved], None], *, dispatch_uid: str) -> None:
+ """Run `handler` after every save of an action, inside the saving transaction.
+
+ For a product that keeps something derived from actions, such as compiled filters that embed an
+ action's matcher. A handler that has slow or external work to do should dispatch a task.
+ """
+ saved_handlers.register(handler, dispatch_uid=dispatch_uid)
+
+
+# AI summaries and embeddings
+
+
+async def alist_actions_to_summarize(
+ *, start_dt: datetime, offset: int | None = None, batch_size: int | None = None
+) -> list[contracts.Action]:
+ """Actions whose AI summary is missing or older than their last edit, in a fixed order.
+
+ Pass both `offset` and `batch_size` for one page, or neither for every action. The order holds
+ while a run summarizes, so a retried page reads the same actions.
+ """
+ queryset = logic.to_summarize(start_dt)
+ if offset is not None or batch_size is not None:
+ if offset is None or batch_size is None:
+ raise ValueError("Cannot provide only offset or only batch_size")
+ queryset = queryset[offset : offset + batch_size]
+ actions: list[contracts.Action] = []
+ async for action in queryset:
+ try:
+ actions.append(_to_contract(action))
+ except Exception as error:
+ # One action with an unreadable stored step must not stop the sync for every other team, so it is
+ # reported and left out. Its page position is kept, because the next page is read by offset.
+ capture_exception(error, additional_properties={"action_id": action.id, "tag": "max_ai"})
+ logger.exception("Error reading action to summarize", error=error, action_id=action.id)
+ return actions
+
+
+async def acount_actions_to_summarize(*, start_dt: datetime) -> int:
+ return await logic.to_summarize(start_dt).acount()
+
+
+async def asave_action_summaries(*, summaries: Mapping[int, str], summarized_at: datetime) -> None:
+ """Store each action's new summary, stamped with the run that wrote it."""
+ if not summaries:
+ return
+ await ActionModel.objects.abulk_update(
+ [
+ ActionModel(id=action_id, last_summarized_at=summarized_at, summary=summary)
+ for action_id, summary in summaries.items()
+ ],
+ ["last_summarized_at", "summary"],
+ )
+
+
+async def alist_actions_to_embed(
+ *, start_dt: datetime, embedding_version: int | None, offset: int, limit: int
+) -> list[contracts.ActionEmbeddingSource]:
+ """Summarized actions whose summary has not reached the vector store at `embedding_version`, oldest edit first."""
+ rows = logic.to_embed(start_dt=start_dt, embedding_version=embedding_version).values(
+ "team_id", "id", "summary", "name", "description", "deleted"
+ )[offset : offset + limit]
+ return [
+ contracts.ActionEmbeddingSource(
+ id=row["id"],
+ team_id=row["team_id"],
+ name=row["name"],
+ description=row["description"],
+ summary=row["summary"],
+ deleted=row["deleted"],
+ )
+ async for row in rows
+ ]
+
+
+async def amark_actions_embedded(
+ *, action_ids: Iterable[int], synced_at: datetime, embedding_version: int | None
+) -> None:
+ """Record that these actions' summaries reached the vector store, at `embedding_version` when given."""
+ updated: list[ActionModel] = []
+ for action_id in action_ids:
+ action = ActionModel(id=action_id, embedding_last_synced_at=synced_at)
+ if embedding_version is not None:
+ action.embedding_version = embedding_version
+ updated.append(action)
+ if not updated:
+ return
+ await ActionModel.objects.abulk_update(
+ updated,
+ ["embedding_last_synced_at", "embedding_version"]
+ if embedding_version is not None
+ else ["embedding_last_synced_at"],
+ )
diff --git a/products/actions/backend/facade/contracts.py b/products/actions/backend/facade/contracts.py
new file mode 100644
index 000000000000..5ddfc42c0d57
--- /dev/null
+++ b/products/actions/backend/facade/contracts.py
@@ -0,0 +1,129 @@
+"""
+Contract types for actions.
+
+Frozen dataclasses and errors that cross the actions boundary. No Django imports.
+
+These use the stdlib dataclass, not the pydantic one: an action's steps come from a JSON column
+that older code wrote, and the HogQL compiler has always read those rows as they are. Validating
+them on the way out would turn a stored step that compiles today into a read that fails.
+"""
+
+import dataclasses
+from collections.abc import Mapping, Sequence
+from datetime import datetime
+from typing import Literal, Optional, get_args
+
+ActionStepMatching = Literal["contains", "regex", "exact"]
+ACTION_STEP_MATCHING_OPTIONS: tuple[ActionStepMatching, ...] = get_args(ActionStepMatching)
+
+
+class ActionNotFound(Exception):
+ """No action with that id exists in the requested scope."""
+
+
[email protected](frozen=True)
+class ActionStep:
+ """One way an event can match an action. The steps of an action are OR-ed together.
+
+ The field names and defaults are the stored step shape, so `ActionStep(**stored_step)` reads a
+ stored step and `dataclasses.asdict(step)` writes one.
+ """
+
+ tag_name: Optional[str] = None
+ text: Optional[str] = None
+ text_matching: Optional[ActionStepMatching] = None
+ href: Optional[str] = None
+ href_matching: Optional[ActionStepMatching] = None
+ selector: Optional[str] = None
+ url: Optional[str] = None
+ url_matching: Optional[ActionStepMatching] = "contains"
+ event: Optional[str] = None
+ properties: Optional[list[dict]] = None
+
+
[email protected](frozen=True, kw_only=True)
+class Action:
+ id: int
+ team_id: int
+ name: Optional[str]
+ description: str
+ steps: tuple[ActionStep, ...]
+ deleted: bool
+ created_by_id: Optional[int]
+ created_at: datetime
+ updated_at: datetime
+ pinned_at: Optional[datetime]
+ last_calculated_at: Optional[datetime]
+ summary: Optional[str]
+
+ def get_step_events(self) -> list[Optional[str]]:
+ """The event each step matches, in step order. A step that matches any event gives None."""
+ return [step.event for step in self.steps]
+
+
[email protected](frozen=True, kw_only=True)
+class ActionCatalogEntry:
+ """An action as a picker lists it: no steps, and the description cut to `short_description`."""
+
+ id: int
+ name: Optional[str]
+ short_description: Optional[str]
+
+
[email protected](frozen=True, kw_only=True)
+class ActionRecentEntry:
+ id: int
+ name: Optional[str]
+ updated_at: Optional[datetime]
+
+
[email protected](frozen=True, kw_only=True)
+class ActionInventory:
+ """How many live actions a team has, and the ones changed most recently."""
+
+ total_count: int
+ recent: tuple[ActionRecentEntry, ...]
+
+
[email protected](frozen=True, kw_only=True)
+class ActionEmbeddingSource:
+ """An action whose summary still has to reach the vector store."""
+
+ id: int
+ team_id: int
+ name: Optional[str]
+ description: str
+ summary: Optional[str]
+ deleted: bool
+
+
[email protected](frozen=True, kw_only=True)
+class ActionBytecode:
+ """What the last save compiled an action's steps to. `bytecode` is None when compiling failed."""
+
+ bytecode: Optional[list]
+ bytecode_error: Optional[str]
+
+
[email protected](frozen=True, kw_only=True)
+class ActionAiState:
+ """Where an action stands in the AI summary and embedding sync."""
+
+ summary: Optional[str]
+ last_summarized_at: Optional[datetime]
+ embedding_last_synced_at: Optional[datetime]
+ embedding_version: Optional[int]
+
+
[email protected](frozen=True, kw_only=True)
+class ActionSaved:
+ """An action row was written. Handlers registered with `on_action_saved` receive this."""
+
+ action_id: int
+ team_id: int
+ created: bool
+
+
+def steps_from_json(steps_json: Optional[Sequence[Mapping]]) -> tuple[ActionStep, ...]:
+ """Steps in the stored JSON shape, as contracts. An unknown key raises `TypeError`, as it always has."""
+ return tuple(ActionStep(**step) for step in steps_json or [])
diff --git a/products/actions/backend/facade/testing.py b/products/actions/backend/facade/testing.py
new file mode 100644
index 000000000000..aca4a7d97bd6
--- /dev/null
+++ b/products/actions/backend/facade/testing.py
@@ -0,0 +1,157 @@
+"""Test-support facade for actions.
+
+Suites outside this product plant, edit and remove actions through here instead of importing the
+model. Each helper goes through the model's save, so an action written here compiles its bytecode
+and fires the same save hooks as one written through the API.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from datetime import datetime
+from typing import TYPE_CHECKING
+
+from asgiref.sync import sync_to_async
+
+from products.actions.backend.facade import contracts
+from products.actions.backend.facade.api import _to_contract
+from products.actions.backend.models.action import Action
+
+if TYPE_CHECKING:
+ from posthog.models import Team, User
+
+__all__ = [
+ "acreate_action",
+ "aget_action_ai_state",
+ "create_action",
+ "delete_action",
+ "get_action_ai_state",
+ "get_action_bytecode",
+ "update_action",
+]
+
+_UNSET = object()
+
+
+def create_action(
+ *,
+ id: int | None = None,
+ team: Team | None = None,
+ team_id: int | None = None,
+ name: str | None = None,
+ steps_json: Sequence[Mapping[str, object]] | None = None,
+ description: str = "",
+ created_by: User | None = None,
+ deleted: bool = False,
+ pinned_at: datetime | str | None = None,
+ last_calculated_at: datetime | str | None = None,
+ summary: str | None = None,
+ last_summarized_at: datetime | str | None = None,
+ embedding_last_synced_at: datetime | str | None = None,
+ embedding_version: int | None = None,
+ post_to_slack: bool = False,
+ slack_message_format: str = "",
+) -> contracts.Action:
+ """Create an action with its steps in the stored JSON shape, and return it.
+
+ Give the team as `team` or as `team_id`. Fields left as None take the model defaults; a timestamp may be an
+ ISO string, as the model accepts. `id` pins the
+ primary key, for a fixture that a stored payload names by a fixed id.
+ """
+ if (team is None) == (team_id is None):
+ raise ValueError("Pass exactly one of team and team_id")
+ optional_fields = {
+ "id": id,
+ "pinned_at": pinned_at,
+ "last_calculated_at": last_calculated_at,
+ "summary": summary,
+ "last_summarized_at": last_summarized_at,
+ "embedding_last_synced_at": embedding_last_synced_at,
+ "embedding_version": embedding_version,
+ }
+ action = Action.objects.create(
+ **({"team": team} if team is not None else {"team_id": team_id}),
+ name=name,
+ steps_json=[dict(step) for step in steps_json] if steps_json is not None else None,
+ description=description,
+ created_by=created_by,
+ deleted=deleted,
+ post_to_slack=post_to_slack,
+ slack_message_format=slack_message_format,
+ **{field: value for field, value in optional_fields.items() if value is not None},
+ )
+ return _to_contract(action)
+
+
+acreate_action = sync_to_async(create_action)
+
+
+def update_action(
+ action: contracts.Action,
+ *,
+ name: object = _UNSET,
+ description: object = _UNSET,
+ steps_json: object = _UNSET,
+ deleted: object = _UNSET,
+ pinned_at: object = _UNSET,
+ last_calculated_at: object = _UNSET,
+ summary: object = _UNSET,
+ last_summarized_at: object = _UNSET,
+ updated_at: object = _UNSET,
+ embedding_last_synced_at: object = _UNSET,
+ embedding_version: object = _UNSET,
+) -> contracts.Action:
+ """Change the given fields and save, as an edit through the API would. Returns the saved action.
+
+ `updated_at` is stamped by every save, so a backdated one is written with a separate update.
+ """
+ row = Action.objects.get(team_id=action.team_id, pk=action.id)
+ fields = {
+ "name": name,
+ "description": description,
+ "steps_json": steps_json,
+ "deleted": deleted,
+ "pinned_at": pinned_at,
+ "last_calculated_at": last_calculated_at,
+ "summary": summary,
+ "last_summarized_at": last_summarized_at,
+ "embedding_last_synced_at": embedding_last_synced_at,
+ "embedding_version": embedding_version,
+ }
+ for field, value in fields.items():
+ if value is not _UNSET:
+ setattr(row, field, value)
+ row.save()
+ if updated_at is not _UNSET:
+ Action.objects.filter(team_id=action.team_id, pk=action.id).update(updated_at=updated_at)
+ row.refresh_from_db()
+ return _to_contract(row)
+
+
+def delete_action(action: contracts.Action) -> None:
+ """Remove the action row, as a team deletion does. The API only ever soft-deletes."""
+ Action.objects.get(team_id=action.team_id, pk=action.id).delete()
+
+
+def get_action_bytecode(action: contracts.Action) -> contracts.ActionBytecode:
+ """The bytecode the last save compiled for the action, or the error it hit."""
+ bytecode, bytecode_error = Action.objects.values_list("bytecode", "bytecode_error").get(
+ team_id=action.team_id, pk=action.id
+ )
+ return contracts.ActionBytecode(bytecode=bytecode, bytecode_error=bytecode_error)
+
+
+def get_action_ai_state(action: contracts.Action) -> contracts.ActionAiState:
+ """Where the action stands in the AI summary and embedding sync."""
+ summary, last_summarized_at, embedding_last_synced_at, embedding_version = Action.objects.values_list(
+ "summary", "last_summarized_at", "embedding_last_synced_at", "embedding_version"
+ ).get(team_id=action.team_id, pk=action.id)
+ return contracts.ActionAiState(
+ summary=summary,
+ last_summarized_at=last_summarized_at,
+ embedding_last_synced_at=embedding_last_synced_at,
+ embedding_version=embedding_version,
+ )
+
+
+aget_action_ai_state = sync_to_async(get_action_ai_state)
diff --git a/products/actions/backend/api/__init__.py b/products/actions/backend/logic/__init__.py
similarity index 100%
rename from products/actions/backend/api/__init__.py
rename to products/actions/backend/logic/__init__.py
diff --git a/products/actions/backend/logic/actions.py b/products/actions/backend/logic/actions.py
new file mode 100644
index 000000000000..a19ac88e20a9
--- /dev/null
+++ b/products/actions/backend/logic/actions.py
@@ -0,0 +1,188 @@
+"""Queries and writes over the action model. The facade maps what these return to contracts."""
+
+from __future__ import annotations
+
+from collections.abc import Collection, Mapping, Sequence
+from datetime import datetime
+from typing import TYPE_CHECKING, Any
+
+from django.db.models import F, Q, QuerySet
+from django.db.models.functions import Substr
+
+from posthog.helpers.full_text_search import build_rank
+
+from products.actions.backend.facade.contracts import ActionCatalogEntry
+from products.actions.backend.models.action import Action
+
+if TYPE_CHECKING:
+ from posthog.models import Team, User
+
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+SEARCH_FIELDS: dict[str, Any] = {"name": "A", "description": "C"}
+SEARCH_RANK_THRESHOLD = 0.05
+CATALOG_DESCRIPTION_LENGTH = 200
+
+
+def scoped(*, project_id: int | None, team_id: int | None) -> QuerySet[Action]:
+ """Actions in one project, or in one team. A caller must say which, because both are in use and
+ they differ for a child environment: actions live on the project's root team."""
+ if project_id is not None and team_id is not None:
+ raise ValueError("Scope actions by project_id or by team_id, not both")
+ if project_id is not None:
+ return Action.objects.filter(team__project_id=project_id)
+ if team_id is not None:
+ return Action.objects.filter(team_id=team_id)
+ raise ValueError("Scope actions by project_id or by team_id")
+
+
+def live_or_all(queryset: QuerySet[Action], *, include_deleted: bool) -> QuerySet[Action]:
+ return queryset if include_deleted else queryset.filter(deleted=False)
+
+
+def top_actions(*, project_id: int, limit: int) -> QuerySet[Action]:
+ """Pinned actions first, then the most recently calculated: the order web analytics reads goals in."""
+ return Action.objects.filter(team__project_id=project_id, deleted=False).order_by(
+ "pinned_at", "-last_calculated_at"
+ )[:limit]
+
+
+def team_id_of(*, action_id: int, include_deleted: bool) -> int | None:
+ # nosemgrep: idor-lookup-without-team (callers hold an id from a trusted source and need the owning team)
+ queryset = Action.objects.filter(id=action_id)
+ if not include_deleted:
+ queryset = queryset.filter(deleted=False)
+ return queryset.values_list("team_id", flat=True).first()
+
+
+def readable_ids(
+ *,
+ project_id: int,
+ action_ids: Collection[int],
+ access_control: UserAccessControl,
+ required_level: Any,
+) -> set[int]:
+ return {
+ action.id
+ for action in Action.objects.filter(pk__in=action_ids, team__project_id=project_id)
+ if access_control.check_access_level_for_object(action, required_level)
+ }
+
+
+def accessible_ids(*, team_id: int, action_ids: Collection[int], access_control: UserAccessControl) -> set[int]:
+ return set(
+ access_control.filter_queryset_by_access_level(
+ Action.objects.filter(team_id=team_id, pk__in=action_ids, deleted=False), resource="action"
+ ).values_list("pk", flat=True)
+ )
+
+
+def catalog_entries(
+ *, team_id: int, access_control: UserAccessControl, limit: int, using: str | None
+) -> list[ActionCatalogEntry]:
+ manager = Action.objects.using(using) if using else Action.objects
+ rows = (
+ access_control.filter_queryset_by_access_level(
+ manager.filter(team_id=team_id, deleted=False), resource="action"
+ )
+ .annotate(short_description=Substr("description", 1, CATALOG_DESCRIPTION_LENGTH))
+ .order_by("-updated_at", "-pk")
+ .values_list("pk", "name", "short_description")[:limit]
+ )
+ return [
+ ActionCatalogEntry(id=pk, name=name, short_description=short_description)
+ for pk, name, short_description in rows
+ ]
+
+
+def search(
+ *,
+ project_id: int,
+ query: str | None,
+ access_control: UserAccessControl,
+ limit: int,
+ offset: int,
+ include_deleted: bool,
+ include_count: bool,
+) -> tuple[list[dict[str, Any]], int]:
+ queryset = access_control.filter_queryset_by_access_level(Action.objects.filter(team__project_id=project_id))
+ if not include_deleted:
+ queryset = queryset.filter(deleted=False)
+ if query:
+ queryset = queryset.annotate(rank=build_rank(SEARCH_FIELDS, query, config="simple"))
+ queryset = queryset.filter(rank__gt=SEARCH_RANK_THRESHOLD).order_by("-rank")
+ else:
+ queryset = queryset.order_by(F("name").asc(nulls_first=True))
+ total_count = queryset.count() if include_count else 0
+ fields = ["id", "name", "description", "created_by_id"]
+ if query:
+ fields.append("rank")
+ return list(queryset[offset : offset + limit].values(*fields)), total_count
+
+
+def create(
+ *,
+ team: Team,
+ name: str | None,
+ steps_json: Sequence[Mapping[str, object]] | None,
+ description: str,
+ created_by: User | None,
+ pinned_at: datetime | None,
+) -> Action:
+ return Action.objects.create(
+ team=team,
+ name=name,
+ steps_json=[dict(step) for step in steps_json] if steps_json is not None else None,
+ description=description,
+ created_by=created_by,
+ pinned_at=pinned_at,
+ )
+
+
+def to_summarize(start_dt: datetime) -> QuerySet[Action]:
+ """Actions whose AI summary is missing or older than their last edit, in a fixed order.
+
+ Temporal replays an activity with the same offsets, so the order must not move between attempts:
+ the `last_summarized_at=start_dt` branch keeps rows this run already summarized in the set.
+ """
+ filter_conditions = Q(
+ # Only orgs that have accepted data processing
+ team__organization__is_ai_data_processing_approved=True,
+ # Only actions updated before the start date
+ updated_at__lte=start_dt,
+ ) & (
+ # Never summarized actions but not deleted
+ Q(last_summarized_at__isnull=True, deleted=False)
+ # Actions updated after last summarization workflow
+ | Q(updated_at__gte=F("last_summarized_at"))
+ | Q(last_summarized_at=start_dt)
+ )
+ return Action.objects.filter(filter_conditions).order_by("id", "team_id", "updated_at")
+
+
+def to_embed(*, start_dt: datetime, embedding_version: int | None) -> QuerySet[Action]:
+ query = (
+ # Include only updated actions.
+ Q(last_summarized_at__gt=F("embedding_last_synced_at"))
+ # Or actions that haven't never been synced but have summaries.
+ | (Q(embedding_last_synced_at__isnull=True) & Q(last_summarized_at__isnull=False))
+ )
+
+ # Temporal workflows must be deterministic, so a run started without a version does not look at versions.
+ if embedding_version is not None:
+ query |= (
+ # Or actions that don't have an embedding version.
+ Q(embedding_version__isnull=True)
+ # Or actions with an old embedding version.
+ | Q(embedding_version__lt=embedding_version)
+ )
+
+ return Action.objects.filter(
+ Q(
+ # Include only actions that have been summarized.
+ last_summarized_at__lte=start_dt,
+ # And they must have a summary to prevent infinite loops.
+ summary__isnull=False,
+ )
+ & query
+ ).order_by("updated_at", "id")
diff --git a/products/actions/backend/logic/saved_handlers.py b/products/actions/backend/logic/saved_handlers.py
new file mode 100644
index 000000000000..8f4115f6314c
--- /dev/null
+++ b/products/actions/backend/logic/saved_handlers.py
@@ -0,0 +1,22 @@
+"""The handlers other products register to hear about action saves.
+
+Kept free of model imports, so the action model's own post_save receiver can call into it.
+"""
+
+from collections.abc import Callable
+
+from ..facade.contracts import ActionSaved
+
+ActionSavedHandler = Callable[[ActionSaved], None]
+
+_handlers: dict[str, ActionSavedHandler] = {}
+
+
+def register(handler: ActionSavedHandler, *, dispatch_uid: str) -> None:
+ # Keyed like a Django receiver's dispatch_uid, so a module imported twice registers once.
+ _handlers.setdefault(dispatch_uid, handler)
+
+
+def dispatch(event: ActionSaved) -> None:
+ for handler in list(_handlers.values()):
+ handler(event)
diff --git a/products/actions/backend/models/__init__.py b/products/actions/backend/models/__init__.py
index 8f3d799bf6fa..5b9b8c55b134 100644
--- a/products/actions/backend/models/__init__.py
+++ b/products/actions/backend/models/__init__.py
@@ -1,4 +1,4 @@
-from .action import Action, ActionStepJSON
+from .action import Action
from .action_step import ActionStep
from .selector_match_change import ActionSelectorMatchChange
@@ -6,5 +6,4 @@ __all__ = [
"Action",
"ActionSelectorMatchChange",
"ActionStep",
- "ActionStepJSON",
]
diff --git a/products/actions/backend/models/action.py b/products/actions/backend/models/action.py
index 7cd6088424da..230009543c43 100644
--- a/products/actions/backend/models/action.py
+++ b/products/actions/backend/models/action.py
@@ -1,5 +1,5 @@
-from dataclasses import asdict, dataclass
-from typing import TYPE_CHECKING, Literal, Optional, Union, get_args
+from dataclasses import asdict
+from typing import TYPE_CHECKING, Union
from django.db import models
from django.db.models import QuerySet
@@ -18,28 +18,13 @@ from posthog.models.tagged_items_relation import Taggable
from posthog.models.utils import RootTeamMixin
from posthog.plugins.plugin_server_api import drop_action_on_workers, reload_action_on_workers
+from products.actions.backend.facade.contracts import ActionSaved, ActionStep
+from products.actions.backend.logic import saved_handlers
+
if TYPE_CHECKING:
from posthog.models.team import Team
-ActionStepMatching = Literal["contains", "regex", "exact"]
-ACTION_STEP_MATCHING_OPTIONS: tuple[ActionStepMatching, ...] = get_args(ActionStepMatching)
-
-
-@dataclass
-class ActionStepJSON:
- tag_name: Optional[str] = None
- text: Optional[str] = None
- text_matching: Optional[ActionStepMatching] = None
- href: Optional[str] = None
- href_matching: Optional[ActionStepMatching] = None
- selector: Optional[str] = None
- url: Optional[str] = None
- url_matching: Optional[ActionStepMatching] = "contains"
- event: Optional[str] = None
- properties: Optional[list[dict]] = None
-
-
class Action(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Model):
name = models.CharField(max_length=400, null=True, blank=True)
description = models.TextField(blank=True, default="")
@@ -119,23 +104,23 @@ class Action(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, m
}
@property
- def steps(self) -> list[ActionStepJSON]:
- return [ActionStepJSON(**step) for step in self.steps_json or []]
+ def steps(self) -> list[ActionStep]:
+ return [ActionStep(**step) for step in self.steps_json or []]
@steps.setter
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]
+ # TRICKY: This is a little tricky as DRF will deserialize this here as a dict but typing wise we would expect an ActionStep
+ self.steps_json = [asdict(ActionStep(**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) -> None:
from posthog.hogql.compiler.bytecode import create_bytecode
- from posthog.hogql.property import action_to_expr
+ from posthog.hogql.property import steps_to_expr
try:
- new_bytecode = create_bytecode(action_to_expr(self)).bytecode
+ new_bytecode = create_bytecode(steps_to_expr(self.steps, self.team)).bytecode
if new_bytecode != self.bytecode or self.bytecode_error is not None:
self.bytecode = new_bytecode
self.bytecode_error = None
@@ -150,6 +135,7 @@ class Action(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, m
@receiver(post_save, sender=Action)
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)
+ saved_handlers.dispatch(ActionSaved(action_id=instance.id, team_id=instance.team_id, created=created))
@mutable_receiver(post_delete, sender=Action)
diff --git a/products/actions/backend/models/util.py b/products/actions/backend/models/util.py
deleted file mode 100644
index f3cf2bc4b725..000000000000
--- a/products/actions/backend/models/util.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from collections import (
- Counter,
- Counter as TCounter,
-)
-
-from posthog.models.property import PropertyIdentifier
-from posthog.models.property.parse import parse_property_group_data
-
-from products.actions.backend.models.action import Action
-
-
-def get_action_tables_and_properties(action: Action) -> TCounter[PropertyIdentifier]:
- from posthog.models.property.util import extract_tables_and_properties
-
- result: TCounter[PropertyIdentifier] = Counter()
-
- for action_step in action.steps:
- if action_step.url:
- result[("$current_url", "event", None)] += 1
- result += extract_tables_and_properties(
- parse_property_group_data(action_step.properties or []).flat,
- team_id=action.team_id,
- )
-
- return result
diff --git a/products/actions/backend/presentation/__init__.py b/products/actions/backend/presentation/__init__.py
new file mode 100644
index 000000000000..ed615b086bbb
--- /dev/null
+++ b/products/actions/backend/presentation/__init__.py
@@ -0,0 +1 @@
+"""HTTP presentation layer of the actions product (DRF viewsets and serializers)."""
diff --git a/products/actions/backend/api/test/__init__.py b/products/actions/backend/presentation/views/__init__.py
similarity index 100%
rename from products/actions/backend/api/test/__init__.py
rename to products/actions/backend/presentation/views/__init__.py
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/presentation/views/action.py
similarity index 99%
rename from products/actions/backend/api/action.py
rename to products/actions/backend/presentation/views/action.py
index 717d9e8e1622..a5fdfc3c1d3a 100644
--- a/products/actions/backend/api/action.py
+++ b/products/actions/backend/presentation/views/action.py
@@ -51,8 +51,9 @@ from products.access_control.backend.presentation.access_control import (
AccessControlViewSetMixin,
UserAccessControlSerializerMixin,
)
+from products.actions.backend.facade.contracts import ACTION_STEP_MATCHING_OPTIONS
from products.actions.backend.facade.enums import ACTION_REFERENCE_JSONPATH, ACTIONS_ARRAY_JSONPATH
-from products.actions.backend.models.action import ACTION_STEP_MATCHING_OPTIONS, Action
+from products.actions.backend.models.action import Action
from products.actions.backend.models.selector_match_change import ActionSelectorMatchChange
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cohorts.backend.models.cohort import Cohort
diff --git a/products/actions/backend/routes.py b/products/actions/backend/routes.py
index cdc91746b880..9612cb0e5dd7 100644
--- a/products/actions/backend/routes.py
+++ b/products/actions/backend/routes.py
@@ -1,6 +1,6 @@
from posthog.api.routing import RouterRegistry
-from products.actions.backend.api.action import ActionViewSet
+from products.actions.backend.presentation.views.action import ActionViewSet
def register_routes(routers: RouterRegistry) -> None:
diff --git a/products/actions/backend/tests/__init__.py b/products/actions/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/actions/backend/tests/api/__init__.py b/products/actions/backend/tests/api/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/actions/backend/api/test/__snapshots__/test_action.ambr b/products/actions/backend/tests/api/__snapshots__/test_action.ambr
similarity index 100%
rename from products/actions/backend/api/test/__snapshots__/test_action.ambr
rename to products/actions/backend/tests/api/__snapshots__/test_action.ambr
diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/tests/api/test_action.py
similarity index 99%
rename from products/actions/backend/api/test/test_action.py
rename to products/actions/backend/tests/api/test_action.py
index 2fc58af67635..3e983464e97a 100644
--- a/products/actions/backend/api/test/test_action.py
+++ b/products/actions/backend/tests/api/test_action.py
@@ -21,9 +21,9 @@ from posthog.models import Tag, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, deny_warehouse_table_to_member
-from products.actions.backend.api.action import ActionSerializer, ActionStepJSONSerializer
from products.actions.backend.models.action import Action
from products.actions.backend.models.selector_match_change import ActionSelectorMatchChange
+from products.actions.backend.presentation.views.action import ActionSerializer, ActionStepJSONSerializer
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.facade.testing import create_experiment
@@ -47,7 +47,7 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert "denied_warehouse_table" in response.json()["detail"]
assert not Action.objects.filter(team=self.team, name="internal signup").exists()
- @patch("products.actions.backend.api.action.report_user_action")
+ @patch("products.actions.backend.presentation.views.action.report_user_action")
def test_create_action(self, patch_capture, *args):
response = self.client.post(
f"/api/projects/{self.team.id}/actions/",
@@ -234,7 +234,7 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(Action.objects.count(), count)
@time_machine.travel("2021-12-12", tick=False)
- @patch("products.actions.backend.api.action.report_user_action")
+ @patch("products.actions.backend.presentation.views.action.report_user_action")
def test_update_action(self, patch_capture, *args):
user = self._create_user("test_user_update")
self.client.force_login(user)
diff --git a/products/actions/backend/tests/test_facade.py b/products/actions/backend/tests/test_facade.py
index f434d1af04a5..72ada1c87f50 100644
--- a/products/actions/backend/tests/test_facade.py
+++ b/products/actions/backend/tests/test_facade.py
@@ -1,8 +1,17 @@
+from datetime import UTC, datetime, timedelta
+
from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock
+
+from asgiref.sync import async_to_sync
+from parameterized import parameterized
-from posthog.models import Team
+from posthog.models import Organization, Team
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.actions.backend.facade import api, contracts, testing
from products.actions.backend.facade.api import action_filter_conditions
+from products.actions.backend.logic import saved_handlers
from products.actions.backend.models.action import Action
@@ -31,3 +40,257 @@ class TestActionFilterConditions(APIBaseTest):
theirs = Action.objects.create(team=other_team, name="Theirs", steps_json=[{"event": "checkout completed"}])
assert action_filter_conditions(team=self.team, action_ids=[theirs.id]) == {}
+
+
+class TestActionReads(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ other_org = Organization.objects.create(name="other org")
+ self.other_team = Team.objects.create(organization=other_org, name="other")
+
+ def test_the_contract_carries_the_stored_action(self):
+ model = Action.objects.create(
+ team=self.team,
+ name="Signed up",
+ description="Finished the form",
+ created_by=self.user,
+ steps_json=[{"event": "$pageview", "url": "/signup", "url_matching": "exact"}, {"event": None}],
+ )
+
+ action = api.get_action(action_id=model.id, project_id=self.team.project_id)
+
+ assert action.id == model.id
+ assert action.team_id == self.team.id
+ assert action.name == "Signed up"
+ assert action.description == "Finished the form"
+ assert action.created_by_id == self.user.id
+ assert action.steps == (
+ contracts.ActionStep(event="$pageview", url="/signup", url_matching="exact"),
+ contracts.ActionStep(event=None),
+ )
+ assert action.get_step_events() == ["$pageview", None]
+ assert action.created_at == model.created_at
+
+ @parameterized.expand(
+ [
+ ("by project", {"include_deleted": True}, True),
+ ("live only", {"include_deleted": False}, False),
+ ]
+ )
+ def test_a_deleted_action_is_found_unless_live_only_is_asked(self, _name, kwargs, found):
+ deleted = Action.objects.create(team=self.team, name="Gone", deleted=True)
+
+ if found:
+ assert api.get_action(action_id=deleted.id, project_id=self.team.project_id, **kwargs).deleted
+ else:
+ with self.assertRaises(contracts.ActionNotFound):
+ api.get_action(action_id=deleted.id, project_id=self.team.project_id, **kwargs)
+
+ def test_another_projects_action_is_not_found_in_any_scope(self):
+ theirs = Action.objects.create(team=self.other_team, name="Theirs")
+
+ with self.assertRaises(contracts.ActionNotFound):
+ api.get_action(action_id=theirs.id, project_id=self.team.project_id)
+ with self.assertRaises(contracts.ActionNotFound):
+ api.get_action(action_id=theirs.id, team_id=self.team.id)
+ assert api.get_actions(action_ids=[theirs.id], project_id=self.team.project_id) == []
+ assert api.get_action_names(project_id=self.team.project_id, action_ids=[theirs.id]) == {}
+ assert api.existing_action_ids(project_id=self.team.project_id, action_ids=[theirs.id]) == []
+
+ def test_a_read_must_name_one_scope(self):
+ with self.assertRaises(ValueError):
+ api.get_action(action_id=1)
+ with self.assertRaises(ValueError):
+ api.get_action(action_id=1, project_id=self.team.project_id, team_id=self.team.id)
+
+ def test_name_lookups_follow_the_scope_and_the_deleted_flag(self):
+ live = Action.objects.create(team=self.team, name="Same")
+ deleted = Action.objects.create(team=self.team, name="Same", deleted=True)
+ Action.objects.create(team=self.other_team, name="Same")
+
+ assert [action.id for action in api.find_actions_by_name(team_id=self.team.id, name="Same")] == [live.id]
+ assert [
+ action.id
+ for action in api.find_actions_by_name(project_id=self.team.project_id, name="Same", include_deleted=True)
+ ] == [live.id, deleted.id]
+ assert api.get_action_names(project_id=self.team.project_id, action_ids=[live.id, deleted.id]) == {
+ live.id: "Same",
+ deleted.id: "Same",
+ }
+
+ def test_top_actions_put_pinned_first_then_the_most_recently_calculated(self):
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ older = Action.objects.create(team=self.team, name="older", last_calculated_at=now - timedelta(days=2))
+ newer = Action.objects.create(team=self.team, name="newer", last_calculated_at=now - timedelta(days=1))
+ pinned = Action.objects.create(
+ team=self.team, name="pinned", pinned_at=now, last_calculated_at=now - timedelta(days=9)
+ )
+ Action.objects.create(team=self.team, name="deleted", deleted=True, last_calculated_at=now)
+
+ top = api.list_top_actions(project_id=self.team.project_id, limit=2)
+
+ assert [action.id for action in top] == [pinned.id, newer.id]
+ assert older.id not in {action.id for action in top}
+
+ def test_find_action_team_id_is_unscoped_and_can_skip_deleted(self):
+ theirs = Action.objects.create(team=self.other_team, name="Theirs", deleted=True)
+
+ assert api.find_action_team_id(action_id=theirs.id) == self.other_team.id
+ assert api.find_action_team_id(action_id=theirs.id, include_deleted=False) is None
+
+
+class TestActionAccessReads(APIBaseTest):
+ def test_access_filtered_reads_return_only_live_actions_of_the_team(self):
+ live = Action.objects.create(team=self.team, name="Checkout", description="x" * 300)
+ deleted = Action.objects.create(team=self.team, name="Gone", deleted=True)
+ access_control = UserAccessControl(self.user, team=self.team)
+
+ assert api.accessible_action_ids(
+ team_id=self.team.id, action_ids=[live.id, deleted.id], access_control=access_control
+ ) == {live.id}
+ catalog = api.list_action_catalog(team_id=self.team.id, access_control=access_control, limit=10)
+ assert [(entry.id, entry.name, len(entry.short_description or "")) for entry in catalog] == [
+ (live.id, "Checkout", 200)
+ ]
+ assert api.readable_action_ids(
+ project_id=self.team.project_id, action_ids=[live.id, deleted.id], access_control=access_control
+ ) == {live.id, deleted.id}
+
+ def test_search_ranks_by_name_and_can_leave_deleted_out(self):
+ match = Action.objects.create(team=self.team, name="purchase completed")
+ deleted = Action.objects.create(team=self.team, name="purchase abandoned", deleted=True)
+ Action.objects.create(team=self.team, name="signed up")
+ access_control = UserAccessControl(self.user, team=self.team)
+
+ results, count = api.search_actions(
+ project_id=self.team.project_id, query="purchase", access_control=access_control, limit=10
+ )
+ live_results, live_count = api.search_actions(
+ project_id=self.team.project_id,
+ query="purchase",
+ access_control=access_control,
+ limit=10,
+ include_deleted=False,
+ with_access_levels=True,
+ )
+
+ assert count == 2
+ assert {result["result_id"] for result in results} == {str(match.id), str(deleted.id)}
+ assert live_count == 1
+ assert live_results == [
+ {
+ "type": "action",
+ "result_id": str(match.id),
+ "extra_fields": {"name": "purchase completed", "description": ""},
+ "rank": live_results[0]["rank"],
+ "user_access_level": live_results[0]["user_access_level"],
+ }
+ ]
+
+
+class TestActionWrites(APIBaseTest):
+ def test_create_action_moves_a_child_environment_to_the_root_team_and_compiles(self):
+ child = Team.objects.create(organization=self.organization, project=self.project, name="child")
+ child.parent_team = self.team
+ child.save()
+
+ action = api.create_action(team=child, name="Viewed", steps_json=[{"event": "$pageview"}])
+
+ assert action.team_id == self.team.id
+ assert testing.get_action_bytecode(action).bytecode is not None
+
+ def test_save_handlers_hear_every_save(self):
+ handler = MagicMock()
+ api.on_action_saved(handler, dispatch_uid="test_save_handlers_hear_every_save")
+ try:
+ action = testing.create_action(team=self.team, name="Viewed", steps_json=[{"event": "$pageview"}])
+ testing.update_action(action, name="Renamed")
+ finally:
+ saved_handlers._handlers.pop("test_save_handlers_hear_every_save")
+
+ assert [call.args[0] for call in handler.call_args_list] == [
+ contracts.ActionSaved(action_id=action.id, team_id=self.team.id, created=True),
+ contracts.ActionSaved(action_id=action.id, team_id=self.team.id, created=False),
+ ]
+
+ def test_update_action_recompiles_and_can_backdate(self):
+ action = testing.create_action(team=self.team, name="Viewed", steps_json=[{"event": "$pageview"}])
+ before = testing.get_action_bytecode(action).bytecode
+ backdated = datetime(2020, 1, 1, tzinfo=UTC)
+
+ updated = testing.update_action(action, steps_json=[{"event": "$autocapture"}], updated_at=backdated)
+
+ assert updated.get_step_events() == ["$autocapture"]
+ assert updated.updated_at == backdated
+ assert testing.get_action_bytecode(action).bytecode != before
+
+
+class TestActionSummariesAndEmbeddings(APIBaseTest):
+ def _actions(self) -> list[Action]:
+ return [Action.objects.create(team=self.team, name=f"action {index}") for index in range(3)]
+
+ def test_actions_to_summarize_page_in_a_fixed_order(self):
+ actions = self._actions()
+ now = datetime.now(UTC)
+
+ page = async_to_sync(api.alist_actions_to_summarize)(start_dt=now, offset=1, batch_size=1)
+
+ assert async_to_sync(api.acount_actions_to_summarize)(start_dt=now) == 3
+ assert [action.id for action in page] == [actions[1].id]
+ assert async_to_sync(api.acount_actions_to_summarize)(start_dt=now - timedelta(days=1)) == 0
+ with self.assertRaises(ValueError):
+ async_to_sync(api.alist_actions_to_summarize)(start_dt=now, offset=1)
+
+ def test_an_unreadable_action_is_left_out_of_the_page_without_failing_it(self):
+ readable, unreadable, last = self._actions()
+ Action.objects.filter(id=unreadable.id).update(steps_json=[{"event": "x", "legacy_key": 1}])
+
+ page = async_to_sync(api.alist_actions_to_summarize)(start_dt=datetime.now(UTC), offset=0, batch_size=3)
+
+ assert [action.id for action in page] == [readable.id, last.id]
+
+ def test_deleted_actions_are_summarized_only_after_an_edit(self):
+ never_summarized, edited, _ = self._actions()
+ start_dt = datetime.now(UTC)
+ Action.objects.filter(id=never_summarized.id).update(deleted=True)
+ Action.objects.filter(id=edited.id).update(
+ deleted=True,
+ updated_at=start_dt - timedelta(hours=1),
+ last_summarized_at=start_dt - timedelta(hours=2),
+ )
+
+ page = async_to_sync(api.alist_actions_to_summarize)(start_dt=start_dt + timedelta(hours=1))
+
+ assert never_summarized.id not in {action.id for action in page}
+ assert edited.id in {action.id for action in page}
+
+ def test_an_organization_without_ai_consent_is_never_summarized(self):
+ self._actions()
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save()
+
+ assert async_to_sync(api.acount_actions_to_summarize)(start_dt=datetime.now(UTC)) == 0
+
+ def test_summaries_then_embeddings_round_trip(self):
+ first, second, _ = self._actions()
+ summarized_at = datetime.now(UTC)
+
+ async_to_sync(api.asave_action_summaries)(
+ summaries={first.id: "summary one", second.id: "summary two"}, summarized_at=summarized_at
+ )
+ to_embed = async_to_sync(api.alist_actions_to_embed)(
+ start_dt=summarized_at, embedding_version=None, offset=0, limit=10
+ )
+ async_to_sync(api.amark_actions_embedded)(
+ action_ids=[action.id for action in to_embed], synced_at=summarized_at, embedding_version=2
+ )
+
+ assert [(action.id, action.summary) for action in to_embed] == [
+ (first.id, "summary one"),
+ (second.id, "summary two"),
+ ]
+ assert (
+ async_to_sync(api.alist_actions_to_embed)(start_dt=summarized_at, embedding_version=2, offset=0, limit=10)
+ == []
+ )
+ assert set(Action.objects.filter(embedding_version=2).values_list("id", flat=True)) == {first.id, second.id}
diff --git a/products/actions/tsconfig.json b/products/actions/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/actions/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/autoresearch/backend/dataset/labeling.py b/products/autoresearch/backend/dataset/labeling.py
index aa8a4937df46..5d16fe8391f9 100644
--- a/products/autoresearch/backend/dataset/labeling.py
+++ b/products/autoresearch/backend/dataset/labeling.py
@@ -52,7 +52,7 @@ from posthog.hogql.property import action_to_expr
from posthog.dataclasses import frozen
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
if TYPE_CHECKING:
from posthog.models import Team
@@ -711,7 +711,7 @@ def build_target_condition(
# Scope the lookup to the pipeline's project so a foreign action id can't leak across
# tenants. Actions live on the project's root team, so a team match would miss them
# from any other environment of the same project.
- action = Action.objects.get(id=action_id, team__project_id=team.project_id, deleted=False)
+ action = get_action(action_id=action_id, project_id=team.project_id, include_deleted=False)
if not action.steps:
# action_to_expr compiles an empty step list to a constant true, which would label
# every event in the horizon a positive.
diff --git a/products/autoresearch/backend/dataset/test_target.py b/products/autoresearch/backend/dataset/test_target.py
index f32cdf958b1c..eb88f0584dbf 100644
--- a/products/autoresearch/backend/dataset/test_target.py
+++ b/products/autoresearch/backend/dataset/test_target.py
@@ -8,7 +8,8 @@ from posthog.schema import HogQLQuery
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models import Organization, Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import ActionNotFound
+from products.actions.backend.facade.testing import create_action
from products.autoresearch.backend.dataset.labeling import build_target_condition
from products.autoresearch.backend.presentation.views.serializers import resolve_target
from products.autoresearch.backend.query import run_hogql_rows
@@ -29,7 +30,7 @@ class TestBuildTargetCondition(TeamScopedTestMixin, APIBaseTest):
assert values == {"target": "signed_up"}
def test_action_target_compiles_to_self_contained_fragment(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Interacted with file",
steps_json=[{"event": "uploaded_file"}, {"event": "downloaded_file"}],
@@ -53,9 +54,9 @@ class TestBuildTargetCondition(TeamScopedTestMixin, APIBaseTest):
def test_action_target_is_team_scoped(self):
other_org = Organization.objects.create(name="Other")
other_team = Team.objects.create(organization=other_org, name="Other")
- action = Action.objects.create(team=other_team, name="Foreign", steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=other_team, name="Foreign", steps_json=[{"event": "uploaded_file"}])
# Resolving a foreign action against self.team must not leak it.
- with self.assertRaises(Action.DoesNotExist):
+ with self.assertRaises(ActionNotFound):
build_target_condition(
target_event="", target_definition={"type": "action", "action_id": action.id}, team=self.team
)
@@ -64,7 +65,7 @@ class TestBuildTargetCondition(TeamScopedTestMixin, APIBaseTest):
# Actions are stored on the project's root team, so a pipeline in another
# environment of the same project must still find them.
environment = Team.objects.create(organization=self.organization, project=self.project, name="Env 2")
- action = Action.objects.create(team=self.team, name="Upload", steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=self.team, name="Upload", steps_json=[{"event": "uploaded_file"}])
cond, _values = build_target_condition(
target_event="", target_definition={"type": "action", "action_id": action.id}, team=environment
)
@@ -73,7 +74,7 @@ class TestBuildTargetCondition(TeamScopedTestMixin, APIBaseTest):
def test_action_target_with_no_steps_is_rejected(self):
# action_to_expr compiles an empty step list to a constant true, which would make
# every event in the horizon a positive label.
- action = Action.objects.create(team=self.team, name="Empty", steps_json=[])
+ action = create_action(team=self.team, name="Empty", steps_json=[])
with self.assertRaises(ValueError):
build_target_condition(
target_event="", target_definition={"type": "action", "action_id": action.id}, team=self.team
@@ -91,9 +92,7 @@ class TestResolveTarget(TeamScopedTestMixin, APIBaseTest):
resolve_target(team=self.team, target_event="", target_definition=None)
def test_action_target_backfills_event_from_action_name(self):
- action = Action.objects.create(
- team=self.team, name="Interacted with file", steps_json=[{"event": "uploaded_file"}]
- )
+ action = create_action(team=self.team, name="Interacted with file", steps_json=[{"event": "uploaded_file"}])
event, definition = resolve_target(
team=self.team, target_event="", target_definition={"type": "action", "action_id": action.id}
)
@@ -101,7 +100,7 @@ class TestResolveTarget(TeamScopedTestMixin, APIBaseTest):
assert definition == {"type": "action", "action_id": action.id}
def test_action_target_keeps_explicit_event_label(self):
- action = Action.objects.create(team=self.team, name="Some action", steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=self.team, name="Some action", steps_json=[{"event": "uploaded_file"}])
event, definition = resolve_target(
team=self.team,
target_event="custom label",
@@ -115,7 +114,7 @@ class TestResolveTarget(TeamScopedTestMixin, APIBaseTest):
def test_action_in_a_sibling_environment_of_the_project_resolves(self):
other_environment = Team.objects.create(organization=self.organization, project=self.project, name="Other env")
- action = Action.objects.create(team=self.team, name="Root team action", steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=self.team, name="Root team action", steps_json=[{"event": "uploaded_file"}])
event, definition = resolve_target(
team=other_environment, target_event="", target_definition={"type": "action", "action_id": action.id}
)
@@ -130,7 +129,7 @@ class TestResolveTarget(TeamScopedTestMixin, APIBaseTest):
]
)
def test_action_that_can_match_the_prediction_event_raises(self, _name: str, steps_json: list[dict]):
- action = Action.objects.create(team=self.team, name="Broad", steps_json=steps_json)
+ action = create_action(team=self.team, name="Broad", steps_json=steps_json)
with self.assertRaises(drf_serializers.ValidationError) as ctx:
resolve_target(
team=self.team, target_event="", target_definition={"type": "action", "action_id": action.id}
@@ -140,7 +139,7 @@ class TestResolveTarget(TeamScopedTestMixin, APIBaseTest):
def test_foreign_action_raises(self):
other_org = Organization.objects.create(name="Other")
other_team = Team.objects.create(organization=other_org, name="Other")
- action = Action.objects.create(team=other_team, name="Foreign", steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=other_team, name="Foreign", steps_json=[{"event": "uploaded_file"}])
with self.assertRaises(drf_serializers.ValidationError):
resolve_target(
team=self.team, target_event="", target_definition={"type": "action", "action_id": action.id}
@@ -163,7 +162,7 @@ class TestTargetConditionAgainstClickhouse(ClickhouseTestMixin, APIBaseTest):
_create_event(team=self.team, event=event, distinct_id="u1")
flush_persons_and_events()
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Interacted with file",
steps_json=[{"event": "uploaded_file"}, {"event": "downloaded_file"}],
@@ -186,7 +185,7 @@ class TestTargetConditionAgainstClickhouse(ClickhouseTestMixin, APIBaseTest):
_create_event(team=self.team, event="uploaded_file", distinct_id="u2", properties={"size": "small"})
flush_persons_and_events()
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Large upload",
steps_json=[{"event": "uploaded_file", "properties": [{"key": "size", "value": "large", "type": "event"}]}],
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index 5a69645d62cc..69a01bb994ff 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -32,7 +32,8 @@ from posthog.paging import Page, PageRequest
from posthog.queryset_paging import select_page
from posthog.storage.object_storage import ObjectStorageError
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action, get_actions
+from products.actions.backend.facade.contracts import ActionNotFound
from products.tasks.backend.facade.model_catalogue import REASONING_EFFORT_DISPLAY_NAMES, display_name_for_model
from ..dataset import templates as templates_module
@@ -968,8 +969,8 @@ def resolve_action_target(project_id: int, action_id: Any) -> tuple[str, int]:
observed as an outcome.
"""
try:
- action = Action.objects.get(id=action_id, team__project_id=project_id, deleted=False)
- except (Action.DoesNotExist, ValueError, TypeError, OverflowError):
+ action = get_action(action_id=action_id, project_id=project_id, include_deleted=False)
+ except (ActionNotFound, ValueError, TypeError, OverflowError):
raise PipelineNotFound(f"Action {action_id} was not found in this project.")
step_events = action.get_step_events()
if any(event is None or event == PREDICTION_EVENT_NAME for event in step_events):
@@ -1169,7 +1170,10 @@ def _require_resolvable_target(pipeline: AutoresearchPipeline) -> None:
return
action_id = definition.get("action_id")
action = (
- Action.objects.filter(id=action_id, team__project_id=pipeline.team.project_id, deleted=False).first()
+ next(
+ iter(get_actions(action_ids=[action_id], project_id=pipeline.team.project_id, include_deleted=False)),
+ None,
+ )
if isinstance(action_id, int)
else None
)
@@ -1315,7 +1319,7 @@ def validate_pipeline_online(
_require_resolvable_target(pipeline)
try:
runs = run_online_validation_for_pipeline(pipeline=pipeline, user=user)
- except Action.DoesNotExist:
+ except ActionNotFound:
raise AutoresearchConflict("The pipeline's target action no longer exists.")
return [_run_to_contract(run) for run in runs]
@@ -1492,7 +1496,7 @@ def start_training(
user_id=user_id,
kickoff_reason=AutoresearchTrainingRun.KickoffReason.MANUAL,
)
- except Action.DoesNotExist:
+ except ActionNotFound:
raise AutoresearchConflict("The pipeline's target action no longer exists.")
except (ValueError, SandboxInferenceError) as exc:
# run_training refuses an unresolvable target or a departed creator before any write.
diff --git a/products/autoresearch/backend/management/commands/autoresearch_seed_demo.py b/products/autoresearch/backend/management/commands/autoresearch_seed_demo.py
index 3a283cbf8b2f..720e25ff1f87 100644
--- a/products/autoresearch/backend/management/commands/autoresearch_seed_demo.py
+++ b/products/autoresearch/backend/management/commands/autoresearch_seed_demo.py
@@ -52,7 +52,8 @@ from posthog.models.person.util import create_person, create_person_distinct_id
from posthog.models.team.team import Team
from posthog.uuidt import UUIDT
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import create_action, find_actions_by_name
+from products.actions.backend.facade.contracts import steps_from_json
TARGET_EVENT = "report_shared"
# The horizon the printed follow-up commands use.
@@ -373,12 +374,13 @@ class Command(BaseCommand):
# Action rows live on the project's root team; a child environment would miss them and duplicate the action.
root_team = team.parent_team or team
# Names are not unique, so reuse only an action with the seeded steps and never edit someone else's.
- same_name = Action.objects.filter(team=root_team, name=ACTION_NAME, deleted=False).order_by("pk")
- action = next((a for a in same_name if a.steps_json == steps_json), None)
+ same_name = find_actions_by_name(team_id=root_team.id, name=ACTION_NAME)
+ seeded_steps = steps_from_json(steps_json)
+ action = next((a for a in same_name if a.steps == seeded_steps), None)
if action is not None:
action_status = "already existed"
else:
- action = Action.objects.create(
+ action = create_action(
team=root_team,
name=ACTION_NAME,
description=f"`{TARGET_EVENT}` with share_type = external. Seeded by autoresearch_seed_demo.",
@@ -387,7 +389,7 @@ class Command(BaseCommand):
action_status = "created"
self.stdout.write(self.style.SUCCESS(f"\n✓ Wrote {len(users)} persons and {total_events} events."))
- self.stdout.write(f" Action '{ACTION_NAME}' id={action.pk} ({action_status})")
+ self.stdout.write(f" Action '{ACTION_NAME}' id={action.id} ({action_status})")
member = team.all_users_with_access().order_by("pk").first()
user_id = str(member.pk) if member else "<USER_ID>"
self.stdout.write("\nNext, once ingestion has caught up (it runs asynchronously):")
diff --git a/products/autoresearch/backend/temporal/workflows.py b/products/autoresearch/backend/temporal/workflows.py
index 966711b4c78d..fc08ecb48b5b 100644
--- a/products/autoresearch/backend/temporal/workflows.py
+++ b/products/autoresearch/backend/temporal/workflows.py
@@ -33,7 +33,7 @@ with workflow.unsafe.imports_passed_through():
from posthog.models.team.team import Team
from posthog.models.user import User
- from products.actions.backend.models.action import Action
+ from products.actions.backend.facade.contracts import ActionNotFound
from products.autoresearch.backend.access import has_autoresearch_access
from products.autoresearch.backend.dataset.labeling import build_target_condition
from products.autoresearch.backend.evaluation.online_validation import run_online_validation_for_pipeline
@@ -209,7 +209,7 @@ def _champion_for_inference(pipeline: AutoresearchPipeline) -> AutoresearchModel
build_target_condition(
target_event=pipeline.target_event, target_definition=pipeline.target_definition, team=pipeline.team
)
- except (ValueError, Action.DoesNotExist) as exc:
+ except (ValueError, ActionNotFound) as exc:
raise ApplicationError(f"The pipeline's target cannot be resolved: {exc}", non_retryable=True)
model = (
AutoresearchModel.objects.filter(pipeline=pipeline, role=AutoresearchModel.Role.CHAMPION)
@@ -947,7 +947,7 @@ def activity_kickoff_training(inp: KickoffTrainingInput) -> KickoffTrainingResul
rescue=rescue,
kickoff_reason=kickoff_reason,
)
- except (ValueError, SandboxInferenceError, Action.DoesNotExist) as exc:
+ except (ValueError, SandboxInferenceError, ActionNotFound) as exc:
# run_training refuses a departed creator or an unresolvable target before it writes
# anything. A retry cannot fix either, so these report instead of raising.
return KickoffTrainingResult(kicked_off=False, reason="not_launchable", error=str(exc))
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index 3703ce71d9a7..4ebaebcc2286 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -20,7 +20,8 @@ from rest_framework.response import Response
from posthog.models import Organization, Team
from posthog.storage.object_storage import ObjectStorageError
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import ActionNotFound
+from products.actions.backend.facade.testing import create_action, update_action
from products.autoresearch.backend.dataset.templates import TEMPLATES
from products.autoresearch.backend.dataset.validation import ValidationResult, ValidationWarning
from products.autoresearch.backend.facade import api
@@ -122,9 +123,7 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
assert AutoresearchPipeline.objects.filter(team=self.team, name="My Pipeline").exists()
def test_create_pipeline_with_action_target(self):
- action = Action.objects.create(
- team=self.team, name="Interacted with file", steps_json=[{"event": "uploaded_file"}]
- )
+ action = create_action(team=self.team, name="Interacted with file", steps_json=[{"event": "uploaded_file"}])
resp = self.client.post(
f"{self.base_url}/",
{
@@ -144,7 +143,7 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
def test_create_pipeline_with_foreign_action_rejected(self):
other_org = Organization.objects.create(name="Other Org")
other_team = Team.objects.create(organization=other_org, name="Other Team")
- action = Action.objects.create(team=other_team, name="Foreign", steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=other_team, name="Foreign", steps_json=[{"event": "uploaded_file"}])
resp = self.client.post(
f"{self.base_url}/",
{"name": "Bad", "target_definition": {"type": "action", "action_id": action.id}},
@@ -153,9 +152,7 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
assert resp.status_code == status.HTTP_400_BAD_REQUEST
def test_create_pipeline_with_deleted_action_rejected(self):
- action = Action.objects.create(
- team=self.team, name="Gone", steps_json=[{"event": "uploaded_file"}], deleted=True
- )
+ action = create_action(team=self.team, name="Gone", steps_json=[{"event": "uploaded_file"}], deleted=True)
resp = self.client.post(
f"{self.base_url}/",
{"name": "Bad", "target_definition": {"type": "action", "action_id": action.id}},
@@ -798,9 +795,7 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
def test_action_targets_need_the_action_scope(
self, _name: str, path: str, scopes: list[str], ok_status: int, _mock: MagicMock
):
- action = Action.objects.create(
- team=self.team, name="Interacted with file", steps_json=[{"event": "uploaded_file"}]
- )
+ action = create_action(team=self.team, name="Interacted with file", steps_json=[{"event": "uploaded_file"}])
body = {"name": "Action Pipeline", "target_definition": {"type": "action", "action_id": action.id}}
self.client.logout()
without = self.create_personal_api_key_with_scopes(scopes)
@@ -949,7 +944,7 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
]
)
def test_action_target_actions_need_the_action_scope(self, path: str, ok_status: int):
- action = Action.objects.create(team=self.team, name="Uploaded", steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=self.team, name="Uploaded", steps_json=[{"event": "uploaded_file"}])
pipeline = self._make_pipeline(
target_event="Uploaded", target_definition={"type": "action", "action_id": action.id}
)
@@ -1005,7 +1000,7 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
pipeline = self._make_trained_pipeline()
with patch(
"products.autoresearch.backend.evaluation.online_validation.run_online_validation_for_pipeline",
- side_effect=Action.DoesNotExist,
+ side_effect=ActionNotFound,
):
resp = self.client.post(f"{self.base_url}/{pipeline.id}/validate_online/")
assert resp.status_code == status.HTTP_400_BAD_REQUEST
@@ -1019,15 +1014,14 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
]
)
def test_scoring_actions_refuse_a_stale_target_action(self, _name: str, path: str, staleness: str):
- action = Action.objects.create(team=self.team, name="Uploaded", steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=self.team, name="Uploaded", steps_json=[{"event": "uploaded_file"}])
pipeline = self._make_trained_pipeline()
pipeline.target_definition = {"type": "action", "action_id": action.id}
pipeline.save(update_fields=["target_definition"])
if staleness == "deleted":
- action.deleted = True
+ update_action(action, deleted=True)
else:
- action.steps_json = []
- action.save()
+ update_action(action, steps_json=[])
with (
patch(f"{_FACADE}._start_inference_workflow") as mock_score,
patch(
@@ -1040,13 +1034,12 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
mock_validate.assert_not_called()
def test_start_training_with_a_deleted_target_action_returns_400(self):
- action = Action.objects.create(team=self.team, name="Uploaded", steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=self.team, name="Uploaded", steps_json=[{"event": "uploaded_file"}])
pipeline = self._make_pipeline(
target_event="Uploaded", target_definition={"type": "action", "action_id": action.id}
)
# The Action API soft-deletes, so the row stays behind.
- action.deleted = True
- action.save(update_fields=["deleted"])
+ update_action(action, deleted=True)
resp = self.client.post(f"{self.base_url}/{pipeline.id}/train/")
assert resp.status_code == status.HTTP_400_BAD_REQUEST
assert not AutoresearchTrainingRun.objects.for_team(self.team.pk).filter(pipeline=pipeline).exists()
@@ -1257,7 +1250,7 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
assert resp.status_code == status.HTTP_400_BAD_REQUEST
def test_oversized_action_name_target_rejected(self):
- action = Action.objects.create(team=self.team, name="x" * 300, steps_json=[{"event": "uploaded_file"}])
+ action = create_action(team=self.team, name="x" * 300, steps_json=[{"event": "uploaded_file"}])
resp = self.client.post(
f"{self.base_url}/",
{"name": "Oversized", "target_definition": {"type": "action", "action_id": action.id}},
diff --git a/products/autoresearch/backend/training/runner.py b/products/autoresearch/backend/training/runner.py
index 0407ffb32f7a..9c63e230aa81 100644
--- a/products/autoresearch/backend/training/runner.py
+++ b/products/autoresearch/backend/training/runner.py
@@ -35,7 +35,8 @@ from posthog.hogql.property import action_to_expr
from posthog.dataclasses import frozen
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
from products.autoresearch.backend.access import has_report_notebook_access
from products.autoresearch.backend.dataset.labeling import TrainingSample, build_target_condition
from products.autoresearch.backend.inference.failures import UnscorableChampion, find_unscorable_champion
@@ -131,7 +132,7 @@ def _describe_target(pipeline: AutoresearchPipeline) -> _TargetDescription:
if definition.get("type") == "action":
action_id = definition.get("action_id")
try:
- action = Action.objects.get(id=int(action_id or 0), team__project_id=pipeline.team.project_id)
+ action = get_action(action_id=int(action_id or 0), project_id=pipeline.team.project_id)
matcher = action_to_expr(action).to_hogql()
spec_line = (
f"action `{_wrap_untrusted(action.name)}` (action_id {action_id}). "
@@ -139,7 +140,7 @@ def _describe_target(pipeline: AutoresearchPipeline) -> _TargetDescription:
)
inline_ref = f"the action `{_wrap_untrusted(action.name)}`"
return _TargetDescription(spec_line=spec_line, inline_ref=inline_ref)
- except (Action.DoesNotExist, TypeError, ValueError):
+ except (ActionNotFound, TypeError, ValueError):
logger.warning("autoresearch_target_action_missing", pipeline_id=str(pipeline.pk), action_id=action_id)
wrapped_event = _wrap_untrusted(pipeline.target_event)
return _TargetDescription(spec_line=f"event `{wrapped_event}`", inline_ref=f"`{wrapped_event}`")
diff --git a/products/autoresearch/backend/training/test_training.py b/products/autoresearch/backend/training/test_training.py
index 377f5ba2c912..f9ddb75b7e0c 100644
--- a/products/autoresearch/backend/training/test_training.py
+++ b/products/autoresearch/backend/training/test_training.py
@@ -11,7 +11,7 @@ from posthog.models.organization import Organization
from posthog.models.team import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.autoresearch.backend.dataset.labeling import TrainingSample
from products.autoresearch.backend.inference.failures import UnscorableChampion
from products.autoresearch.backend.inference.sandbox import SandboxInferenceError
@@ -473,7 +473,7 @@ class TestRunTraining(TeamScopedTestMixin, BaseTest):
)
self.pipeline.created_by = outsider
else:
- action = Action.objects.create(team=self.team, name="empty", steps_json=[])
+ action = create_action(team=self.team, name="empty", steps_json=[])
self.pipeline.target_definition = {"type": "action", "action_id": action.id}
self.pipeline.save()
diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.py
index b95a213b19a6..a1d88c9923cf 100644
--- a/products/cdp/backend/api/test/test_hog_function.py
+++ b/products/cdp/backend/api/test/test_hog_function.py
@@ -15,7 +15,8 @@ from rest_framework import status
from posthog.models.integration import Integration
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_actions
+from products.actions.backend.facade.testing import create_action
from products.cdp.backend.api.hog_function import (
MAX_HOG_CODE_SIZE_BYTES,
MAX_LOG_TRANSFORMATIONS_PER_TEAM,
@@ -490,8 +491,8 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# Create the action referenced in EXAMPLE_FULL
# Use a high ID to avoid conflicts with auto-incrementing sequence
- if not Action.objects.filter(id=999999, team=self.team).exists():
- Action.objects.create(id=999999, name="Test Action", team=self.team, created_by=self.user)
+ if not get_actions(action_ids=[999999], team_id=self.team.id):
+ create_action(id=999999, name="Test Action", team=self.team, created_by=self.user)
def _get_function_activity(
self,
@@ -1712,7 +1713,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"products.access_control.backend.facade.user_access_control.UserAccessControl.access_controls_supported", True
)
def test_filter_action_needs_viewer_access_unless_already_used(self, filter_list: str, id_type: type):
- action = Action.objects.create(
+ action = create_action(
team=self.team, name="restricted", steps_json=[{"event": "$pageview"}], created_by=self.user
)
AccessControl.objects.create(team=self.team, resource="action", resource_id=str(action.id), access_level="none")
@@ -1736,7 +1737,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert edited.status_code == status.HTTP_200_OK, edited.json()
def test_generates_filters_bytecode(self, *args):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="test action",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
@@ -1988,13 +1989,13 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert filtered_actual_activities == expected_activities
def test_list_with_filters_filter(self, *args):
- action1 = Action.objects.create(
+ action1 = create_action(
team=self.team,
name="test action",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
)
- action2 = Action.objects.create(
+ action2 = create_action(
team=self.team,
name="test action",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
@@ -2046,7 +2047,7 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert len(response.json()["results"]) == 1
def test_list_with_filter_groups_filter(self, *args):
- action1 = Action.objects.create(
+ action1 = create_action(
team=self.team,
name="test action",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
diff --git a/products/cdp/backend/api/test/test_hooks.py b/products/cdp/backend/api/test/test_hooks.py
index 809c09b57128..6741b6cc2fa5 100644
--- a/products/cdp/backend/api/test/test_hooks.py
+++ b/products/cdp/backend/api/test/test_hooks.py
@@ -4,7 +4,8 @@ from typing import Any
import pytest
from posthog.test.base import ClickhouseTestMixin
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action
from products.cdp.backend.api.hooks import create_zapier_hog_function, valid_domain
from products.cdp.backend.filters import RUNTIME_CONTRACT
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -23,7 +24,7 @@ class TestHooksAPI(ClickhouseTestMixin, APILicensedTest):
def setUp(self):
super().setUp()
- self.action = Action.objects.create(
+ self.action = create_action(
team=self.team,
name="Test Action",
steps_json=[
diff --git a/products/cdp/backend/apps.py b/products/cdp/backend/apps.py
index 091e5ddb5580..b8830ce13fe4 100644
--- a/products/cdp/backend/apps.py
+++ b/products/cdp/backend/apps.py
@@ -9,3 +9,10 @@ class CdpConfig(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "products.cdp.backend"
label = "cdp"
+
+ def ready(self) -> None:
+ from products.actions.backend.facade.api import on_action_saved # noqa: PLC0415
+ from products.cdp.backend.models.hog_functions.hog_function import action_saved # noqa: PLC0415
+
+ # Compiled filters embed each action's matcher, so they must be rebuilt when an action is saved.
+ on_action_saved(action_saved, dispatch_uid="cdp.hog_functions.action_saved")
diff --git a/products/cdp/backend/filters.py b/products/cdp/backend/filters.py
index b89931b239ed..40ac447c33e1 100644
--- a/products/cdp/backend/filters.py
+++ b/products/cdp/backend/filters.py
@@ -13,7 +13,8 @@ from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
from posthog.dataclasses import frozen
from posthog.models.team.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action, get_actions
+from products.actions.backend.facade.contracts import Action
from products.cohorts.backend.models.cohort import Cohort
COHORT_FILTER_TYPES = frozenset({"cohort", "static-cohort", "precalculated-cohort", "dynamic-cohort"})
@@ -277,8 +278,9 @@ def _build_action_filter_expr(filter: dict, actions: dict[int, Action], team: Te
action_id = int(filter["id"])
action = actions.get(action_id)
if not action:
- action = Action.objects.get(id=action_id, team__project_id=team.project_id)
- return action_to_expr(action)
+ return action_to_expr(get_action(action_id=action_id, project_id=team.project_id))
+ # Callers fetched these with their team joined, so reuse the team rather than read it once per action.
+ return action_to_expr(action, team=team)
except KeyError:
return parse_expr("1 = 2") # No events match
@@ -445,12 +447,7 @@ def compile_filters_expr(filters: Optional[dict], team: Team, actions: Optional[
if actions is None:
# If not provided as an optimization we fetch all actions
- # nosemgrep: idor-lookup-without-team (already scoped by team__project_id)
- actions_list = (
- Action.objects.select_related("team")
- .filter(team__project_id=team.project_id)
- .filter(id__in=filter_action_ids(filters))
- )
+ actions_list = get_actions(project_id=team.project_id, action_ids=filter_action_ids(filters))
actions = {action.id: action for action in actions_list}
return hog_function_filters_to_expr(filters, team, actions)
diff --git a/products/cdp/backend/models/hog_functions/hog_function.py b/products/cdp/backend/models/hog_functions/hog_function.py
index e6e64249335d..b9544ae84b6d 100644
--- a/products/cdp/backend/models/hog_functions/hog_function.py
+++ b/products/cdp/backend/models/hog_functions/hog_function.py
@@ -28,7 +28,7 @@ from posthog.plugins.plugin_server_api import (
)
from posthog.utils import absolute_uri
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import ActionSaved
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.cdp.backend.models.plugin import sync_team_inject_web_apps
from products.cohorts.backend.models.cohort import is_cohort_recalculation_only_save
@@ -382,14 +382,13 @@ def hog_function_saved(sender, instance: HogFunction, created, **kwargs):
reload_hog_functions_on_workers(team_id=instance.team_id, hog_function_ids=[str(instance.id)])
-@receiver(post_save, sender=Action)
-def action_saved(sender, instance: Action, created, **kwargs):
+def action_saved(event: ActionSaved) -> None:
# Whenever an action is saved we want to load all hog functions using it
# and trigger a refresh of the filters bytecode
from products.cdp.backend.tasks.hog_functions import refresh_affected_hog_functions
- refresh_affected_hog_functions.delay(action_id=instance.id)
+ refresh_affected_hog_functions.delay(action_id=event.action_id)
@receiver(post_save, sender=Team)
diff --git a/products/cdp/backend/tasks/hog_functions.py b/products/cdp/backend/tasks/hog_functions.py
index e033c41c714b..741bd885b393 100644
--- a/products/cdp/backend/tasks/hog_functions.py
+++ b/products/cdp/backend/tasks/hog_functions.py
@@ -11,7 +11,8 @@ 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 products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import find_action_team_id, get_actions
+from products.actions.backend.facade.contracts import ActionNotFound
logger = get_logger(__name__)
@@ -26,11 +27,12 @@ def refresh_affected_hog_functions(
affected_hog_functions: list[HogFunction] = []
if action_id:
- action = Action.objects.get(id=action_id)
- team_id = action.team_id
+ team_id = find_action_team_id(action_id=action_id)
+ if team_id is None:
+ raise ActionNotFound(f"Action {action_id} does not exist")
affected_hog_functions = list(
HogFunction.objects.select_related("team")
- .filter(team_id=action.team_id)
+ .filter(team_id=team_id)
.filter(filters__contains={"actions": [{"id": str(action_id)}]})
)
elif cohort_id:
@@ -66,14 +68,11 @@ def refresh_affected_hog_functions(
if not affected_hog_functions:
return 0
- all_related_actions = (
- Action.objects.select_related("team")
- .filter(team_id=team_id)
- .filter(
- id__in=[
- action_id for hog_function in affected_hog_functions for action_id in hog_function.filter_action_ids
- ]
- )
+ all_related_actions = get_actions(
+ team_id=team_id,
+ action_ids=[
+ action_id for hog_function in affected_hog_functions for action_id in hog_function.filter_action_ids
+ ],
)
actions_by_id = {action.id: action for action in all_related_actions}
diff --git a/products/cdp/backend/test/test_filters.py b/products/cdp/backend/test/test_filters.py
index 216ca721306f..b9ceff1270f1 100644
--- a/products/cdp/backend/test/test_filters.py
+++ b/products/cdp/backend/test/test_filters.py
@@ -7,7 +7,8 @@ from parameterized import parameterized
from posthog.hogql.compiler.bytecode import create_bytecode
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action
from products.cdp.backend.filters import (
RUNTIME_CONTRACT,
build_behavioral_event_expr,
@@ -34,7 +35,7 @@ class TestHogFunctionFilters(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
def setUp(self):
super().setUp()
- self.action = Action.objects.create(
+ self.action = create_action(
team=self.team,
name="test action",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
diff --git a/products/cdp/backend/test/test_site_functions.py b/products/cdp/backend/test/test_site_functions.py
index 7f8ac786a5ba..a925c09fc4df 100644
--- a/products/cdp/backend/test/test_site_functions.py
+++ b/products/cdp/backend/test/test_site_functions.py
@@ -15,7 +15,7 @@ from posthog.models.project import Project
from posthog.models.user import User
from posthog.test.test_utils import create_group_type_mapping_without_created_at
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.models.plugin import TranspilerError
from products.cdp.backend.site_functions import get_transpiled_function
@@ -231,9 +231,8 @@ class TestSiteFunctions(TestCase):
@patch("products.cdp.backend.site_functions.transpile", side_effect=mock_transpile)
def test_get_transpiled_function_with_complex_filters(self, mock_transpile_fn):
- action = Action.objects.create(team=self.team, name="Test Action")
- action.steps = [{"event": "$pageview", "url": "https://example.com"}]
- action.save()
+ action = create_action(team=self.team, name="Test Action")
+ update_action(action, steps_json=[{"event": "$pageview", "url": "https://example.com"}])
self.team.test_account_filters = [
{"key": "email", "value": "@posthog.com", "operator": "not_icontains", "type": "person"},
@@ -244,7 +243,7 @@ class TestSiteFunctions(TestCase):
self.hog_function.hog = "export function onEvent(globals) { console.log(globals); }"
self.hog_function.filters = {
"events": [{"id": "$pageview", "name": "$pageview", "type": "events"}],
- "actions": [{"id": str(action.pk), "name": "Test Action", "type": "actions"}],
+ "actions": [{"id": str(action.id), "name": "Test Action", "type": "actions"}],
"filter_test_accounts": True,
}
diff --git a/products/cdp/backend/validation.py b/products/cdp/backend/validation.py
index 6f706d1612d2..91709d460790 100644
--- a/products/cdp/backend/validation.py
+++ b/products/cdp/backend/validation.py
@@ -23,7 +23,7 @@ from posthog.models.integration import POSTHOG_CONNECT_KIND, WAREHOUSE_SOURCE_TY
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_actions
from products.cdp.backend.filters import (
DATA_WAREHOUSE_SOURCES,
FILTER_FUNCTIONS,
@@ -1305,7 +1305,7 @@ def require_viewer_access_to_added_actions(context: dict[str, Any], submitted: A
if not added_ids:
return
- actions = Action.objects.filter(team__project_id=context["get_team"]().project_id, id__in=added_ids)
+ actions = get_actions(project_id=context["get_team"]().project_id, action_ids=added_ids)
denied_ids = user_access_control.denied_object_ids(
"action", [(str(action.id), action.team_id, action.created_by_id) for action in actions], "viewer"
)
@@ -1455,8 +1455,7 @@ class HogFunctionFiltersSerializer(serializers.Serializer):
collected = set(filter_cohort_ids(data))
action_ids = filter_action_ids(data)
if action_ids:
- # nosemgrep: idor-lookup-without-team (scoped by team__project_id)
- for action in Action.objects.filter(id__in=action_ids, team__project_id=team.project_id, deleted=False):
+ for action in get_actions(project_id=team.project_id, action_ids=action_ids, include_deleted=False):
for step in action.steps:
collected |= collect_property_cohort_ids(step.properties or [])
validate_realtime_cohorts(collected, team, require_ready=require_ready)
diff --git a/products/dashboards/backend/api/test/test_run_insights.py b/products/dashboards/backend/api/test/test_run_insights.py
index 127e77b5e466..964f05d2ece2 100644
--- a/products/dashboards/backend/api/test/test_run_insights.py
+++ b/products/dashboards/backend/api/test/test_run_insights.py
@@ -25,7 +25,7 @@ from posthog.caching.insight_result import InsightResult
from posthog.models.organization import Organization
from posthog.models.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.dashboards.backend.access import DashboardAccessMethod
from products.dashboards.backend.api.dashboard import DashboardsViewSet
from products.dashboards.backend.constants import RUN_INSIGHTS_MIN_TILE_CHARS
@@ -128,9 +128,9 @@ class TestDashboardRunInsights(APIBaseTest):
@override_settings(IN_UNIT_TESTING=True)
def test_optimized_format_labels_compared_totals_with_their_ranges_and_saved_series_names(self) -> None:
- action = Action.objects.create(team=self.team, name="Purchase made", steps_json=[{"event": "purchase"}])
+ action = create_action(team=self.team, name="Purchase made", steps_json=[{"event": "purchase"}])
query = _trends_query_dict(
- series=[ActionsNode(id=action.pk, name="Old purchase name")],
+ series=[ActionsNode(id=action.id, name="Old purchase name")],
display=ChartDisplayType.BOLD_NUMBER,
compare_filter=CompareFilter(compare=True),
)
diff --git a/products/demo/backend/logic/legacy/app_data_generator.py b/products/demo/backend/logic/legacy/app_data_generator.py
index 2acc70e21d26..a07715a1cfc6 100644
--- a/products/demo/backend/logic/legacy/app_data_generator.py
+++ b/products/demo/backend/logic/legacy/app_data_generator.py
@@ -8,7 +8,7 @@ from posthog.schema import ActionsNode, DateRange, EventPropertyFilter, FunnelsQ
from posthog.models import EventDefinition, Person, PropertyDefinition
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import create_action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.product_analytics.backend.facade.models import Insight
@@ -27,13 +27,13 @@ class AppDataGenerator(DataGenerator):
PropertyDefinition.objects.get_or_create(team=self.team, name="app_rating", is_numerical=True)
def create_actions_dashboards(self):
- installed_app_action = Action.objects.create(
+ installed_app_action = create_action(
team=self.team, name="Installed App", steps_json=[{"event": "installed_app"}]
)
- rated_app_action = Action.objects.create(team=self.team, name="Rated App", steps_json=[{"event": "rated_app"}])
+ rated_app_action = create_action(team=self.team, name="Rated App", steps_json=[{"event": "rated_app"}])
- Action.objects.create(team=self.team, name="Watched Movie", steps_json=[{"event": "watched_movie"}])
+ create_action(team=self.team, name="Watched Movie", steps_json=[{"event": "watched_movie"}])
dashboard = Dashboard.objects.create(name="App Analytics", pinned=True, team=self.team)
insight = Insight.objects.create(
diff --git a/products/demo/backend/logic/legacy/revenue_data_generator.py b/products/demo/backend/logic/legacy/revenue_data_generator.py
index a7c4067bd1f8..84c270175611 100644
--- a/products/demo/backend/logic/legacy/revenue_data_generator.py
+++ b/products/demo/backend/logic/legacy/revenue_data_generator.py
@@ -16,7 +16,7 @@ from posthog.schema import (
from posthog.models import EventDefinition, Person, PropertyDefinition
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import create_action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.product_analytics.backend.facade.models import Insight
@@ -65,9 +65,9 @@ class RevenueDataGenerator(DataGenerator):
)
def create_actions_dashboards(self):
- purchase_action = Action.objects.create(team=self.team, name="Purchase", steps_json=[{"event": "purchase"}])
+ purchase_action = create_action(team=self.team, name="Purchase", steps_json=[{"event": "purchase"}])
- Action.objects.create(team=self.team, name="Entered Free Trial", steps_json=[{"event": "entered_free_trial"}])
+ create_action(team=self.team, name="Entered Free Trial", steps_json=[{"event": "entered_free_trial"}])
dashboard = Dashboard.objects.create(name="Sales & Revenue", pinned=True, team=self.team)
insight = Insight.objects.create(
diff --git a/products/demo/backend/logic/legacy/web_data_generator.py b/products/demo/backend/logic/legacy/web_data_generator.py
index 29014386cea2..c39db42fb781 100644
--- a/products/demo/backend/logic/legacy/web_data_generator.py
+++ b/products/demo/backend/logic/legacy/web_data_generator.py
@@ -14,7 +14,7 @@ from posthog.schema import ActionsNode, FunnelsQuery, InsightVizNode
from posthog.models import Person, PropertyDefinition
from posthog.models.utils import UUIDT
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import create_action
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.product_analytics.backend.facade.models import Insight
@@ -36,7 +36,7 @@ class WebDataGenerator(DataGenerator):
PropertyDefinition.objects.get_or_create(team=self.team, name="$browser")
def create_actions_dashboards(self):
- homepage = Action.objects.create(
+ homepage = create_action(
team=self.team,
name="Hogflix homepage view",
steps_json=[
@@ -48,7 +48,7 @@ class WebDataGenerator(DataGenerator):
],
)
- user_signed_up = Action.objects.create(
+ user_signed_up = create_action(
team=self.team,
name="Hogflix signed up",
steps_json=[
@@ -61,7 +61,7 @@ class WebDataGenerator(DataGenerator):
],
)
- user_paid = Action.objects.create(
+ user_paid = create_action(
team=self.team,
name="Hogflix paid",
steps_json=[
diff --git a/products/demo/backend/logic/products/hedgebox/matrix.py b/products/demo/backend/logic/products/hedgebox/matrix.py
index 7b67269c516e..1aaf2c55e13b 100644
--- a/products/demo/backend/logic/products/hedgebox/matrix.py
+++ b/products/demo/backend/logic/products/hedgebox/matrix.py
@@ -56,7 +56,7 @@ from posthog.models.oauth_provisioning import ProvisioningConfig
from posthog.scopes import UNPRIVILEGED_SCOPES
from posthog.storage import object_storage
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
@@ -253,7 +253,7 @@ class HedgeboxMatrix(Matrix):
team.session_recording_opt_in = True # Also see: the tools/hedgebox-dummy/ app
# Actions
- interacted_with_file_action = Action.objects.create(
+ interacted_with_file_action = create_action(
name="Interacted with file",
team=team,
description="Logged-in interaction with a file.",
@@ -273,7 +273,7 @@ class HedgeboxMatrix(Matrix):
},
],
)
- Action.objects.create(
+ create_action(
name="Visited Marius Tech Tips campaign",
team=team,
description="Visited page of the campaign we did with Marius Tech Tips, the best YouTube channel for tech tips.",
@@ -424,7 +424,7 @@ class HedgeboxMatrix(Matrix):
custom_name="Signed up",
),
ActionsNode(
- id=interacted_with_file_action.pk,
+ id=interacted_with_file_action.id,
name=interacted_with_file_action.name,
),
EventsNode(
@@ -488,7 +488,7 @@ class HedgeboxMatrix(Matrix):
type=EntityType.EVENTS,
),
returningEntity=RetentionEntity(
- id=str(interacted_with_file_action.pk),
+ id=str(interacted_with_file_action.id),
name=interacted_with_file_action.name,
type=EntityType.ACTIONS,
),
@@ -525,7 +525,7 @@ class HedgeboxMatrix(Matrix):
source=LifecycleQuery(
series=[
ActionsNode(
- id=interacted_with_file_action.pk,
+ id=interacted_with_file_action.id,
name=interacted_with_file_action.name,
math=BaseMathType.TOTAL,
)
diff --git a/products/experiments/backend/health/test/test_exposure_columns.py b/products/experiments/backend/health/test/test_exposure_columns.py
index 9d763d1cb0d7..5aaa69ef04f7 100644
--- a/products/experiments/backend/health/test/test_exposure_columns.py
+++ b/products/experiments/backend/health/test/test_exposure_columns.py
@@ -15,7 +15,7 @@ from posthog.models.event.new_events_schema import events_route_scope
from posthog.models.property import TableColumn
from posthog.schema_enums import MaterializationMode
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.experiments.backend.health.context import ExposureFilterSource
from products.experiments.backend.health.exposure_columns import load_filters_without_column
from products.experiments.backend.models.experiment import Experiment
@@ -239,7 +239,7 @@ class TestLoadFiltersWithoutColumn(BaseTest):
def test_names_the_filters_of_an_action(
self, _name: str, criteria: Callable[[dict[str, Any]], dict[str, Any]], expected: list[str]
) -> None:
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Started checkout",
steps_json=[
@@ -251,7 +251,7 @@ class TestLoadFiltersWithoutColumn(BaseTest):
experiment.exposure_criteria = {
"filterTestAccounts": False,
**criteria(
- {"kind": "ActionsNode", "id": action.pk, "properties": [_filter("source", "event")]},
+ {"kind": "ActionsNode", "id": action.id, "properties": [_filter("source", "event")]},
),
}
diff --git a/products/experiments/backend/hogql_queries/base_query_utils.py b/products/experiments/backend/hogql_queries/base_query_utils.py
index 707d86af8ef6..fa68849150d0 100644
--- a/products/experiments/backend/hogql_queries/base_query_utils.py
+++ b/products/experiments/backend/hogql_queries/base_query_utils.py
@@ -30,7 +30,8 @@ from posthog.hogql.property import action_to_expr, property_to_expr
from posthog.clickhouse.query_tagging import tag_contains_user_hogql
from posthog.models.team.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
from products.ai_observability.backend.facade.api import resolve_evaluation_pass_markers
from products.experiments.backend.hogql_queries.hogql_aggregation_utils import (
contains_aggregation,
@@ -176,9 +177,9 @@ def event_or_action_to_filter(
) -> ast.Expr:
if isinstance(entity_node, ActionsNode):
try:
- action = Action.objects.get(pk=int(entity_node.id), team__project_id=team.project_id)
+ action = get_action(action_id=int(entity_node.id), project_id=team.project_id)
event_filter = action_to_expr(action)
- except Action.DoesNotExist:
+ except ActionNotFound:
# A missing action matches no events, so that the query still runs.
event_filter = ast.Constant(value=False)
else:
diff --git a/products/experiments/backend/hogql_queries/experiment_query_builder.py b/products/experiments/backend/hogql_queries/experiment_query_builder.py
index 5e4a53e5d681..5b525e0ea344 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_builder.py
@@ -26,7 +26,7 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.team.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_actions
from products.experiments.backend.hogql_queries.breakdown_injector import BreakdownInjector
from products.experiments.backend.hogql_queries.cuped_config import CupedQueryConfig
from products.experiments.backend.hogql_queries.experiment_cuped_query_builder import CupedQueryBuilder
@@ -149,7 +149,7 @@ def metric_reads_flag_call(
action_ids = [int(source.id) for source in sources if isinstance(source, ActionsNode)]
return bool(action_ids) and any(
step.event == DEFAULT_EXPOSURE_EVENT
- for action in Action.objects.filter(pk__in=action_ids, team__project_id=team.project_id)
+ for action in get_actions(action_ids=action_ids, project_id=team.project_id)
for step in action.steps
)
diff --git a/products/experiments/backend/hogql_queries/exposure_query_logic.py b/products/experiments/backend/hogql_queries/exposure_query_logic.py
index 778c8da94b9d..9666527f4659 100644
--- a/products/experiments/backend/hogql_queries/exposure_query_logic.py
+++ b/products/experiments/backend/hogql_queries/exposure_query_logic.py
@@ -22,7 +22,8 @@ from posthog.hogql.property import action_to_expr, operator_is_negative, propert
from posthog.models.team.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
logger = logging.getLogger(__name__)
@@ -341,9 +342,9 @@ def _get_event_name_from_config(
def _build_action_filter(action_id: int, team: Team) -> ast.Expr:
"""Build filter expression for an action, returning False if action not found."""
try:
- action = Action.objects.get(pk=action_id, team=team)
+ action = get_action(action_id=action_id, team_id=team.pk)
return action_to_expr(action)
- except Action.DoesNotExist:
+ except ActionNotFound:
logger.warning(f"Action {action_id} not found for team {team.id}. Exposure query will return no results.")
return ast.Constant(value=False)
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py
index 611bd5897e42..10acb17ce998 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py
@@ -27,7 +27,7 @@ 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.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.util import count_cohort_members
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
@@ -257,8 +257,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
experiment = self.create_experiment(feature_flag=feature_flag)
experiment.stats_config = {"method": "frequentist"}
- action = Action.objects.create(name="purchase", team=self.team, steps_json=[{"event": "purchase"}])
- action.save()
+ action = create_action(name="purchase", team=self.team, steps_json=[{"event": "purchase"}])
metric = ExperimentMeanMetric(
source=ActionsNode(id=action.id),
@@ -728,12 +727,11 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):
feature_flag_property = f"$feature/{feature_flag.key}"
# Create an action for purchase events with specific properties
- action = Action.objects.create(
+ action = create_action(
name="Qualified Purchase",
team=self.team,
steps_json=[{"event": "purchase", "properties": [{"key": "plan", "value": "premium", "type": "event"}]}],
)
- action.save()
for variant, purchase_count in [("control", 6), ("test", 8)]:
for i in range(10):
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py
index 073d7e3ae069..6ff0cc4fe9bf 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py
@@ -40,7 +40,7 @@ from posthog.test.test_journeys import journeys_for
from products.access_control.backend.facade.api import upsert_property_access_control
from products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInput
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY
from products.experiments.backend.hogql_queries.experiment_exposures_query_runner import ExperimentExposuresQueryRunner
from products.experiments.backend.hogql_queries.exposure_query_logic import (
@@ -1273,7 +1273,7 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
def test_exposure_query_with_action_as_exposure_criteria(self, _name, use_precomputation):
self._setup_precomputation_test(use_precomputation)
# Create an action for purchase events with specific properties
- action = Action.objects.create(
+ action = create_action(
name="Qualified Purchase",
team=self.team,
steps_json=[{"event": "purchase", "properties": [{"key": "plan", "value": "premium", "type": "event"}]}],
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py
index ab23a65a997b..4112b7410d7d 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py
@@ -31,7 +31,7 @@ from posthog.schema import (
from posthog.constants import GroupTypeIndex
from posthog.test.test_utils import create_group_type_mapping_without_created_at
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
@@ -1444,8 +1444,7 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):
flush_persons_and_events()
- action = Action.objects.create(name="purchase action", team=self.team, steps_json=[{"event": "purchase"}])
- action.save()
+ action = create_action(name="purchase action", team=self.team, steps_json=[{"event": "purchase"}])
metric = ExperimentFunnelMetric(
series=[
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py
index 024ced5b53ee..5c43658c29f4 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py
@@ -23,7 +23,7 @@ from posthog.schema import (
from posthog.test.test_journeys import journeys_for
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.ai_observability.backend.models.evaluations import Evaluation
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
@@ -849,10 +849,7 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
ff_property = f"$feature/{feature_flag.key}"
# Create an action for purchase events
- purchase_action = Action.objects.create(
- name="Purchase Action", team=self.team, steps_json=[{"event": "purchase"}]
- )
- purchase_action.save()
+ purchase_action = create_action(name="Purchase Action", team=self.team, steps_json=[{"event": "purchase"}])
# Create a ratio metric: action-based purchase revenue / event-based page views
# This demonstrates using ActionsNode vs EventsNode as different source types
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_query_builder.py b/products/experiments/backend/hogql_queries/test/test_experiment_query_builder.py
index ede5eb8ef200..f588cb30429e 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_query_builder.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_query_builder.py
@@ -34,7 +34,7 @@ from posthog.hogql.parser import parse_select
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.team.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
LazyComputationQuery,
LazyComputationTable,
@@ -79,7 +79,7 @@ BROWSER = [Breakdown(property="$browser")]
def _mean_on_action(team: Team) -> ExperimentMeanMetric:
- action = Action.objects.create(team=team, name="purchase", steps_json=[{"event": "purchase"}])
+ action = create_action(team=team, name="purchase", steps_json=[{"event": "purchase"}])
return ExperimentMeanMetric(source=ActionsNode(id=action.id))
diff --git a/products/experiments/backend/hogql_queries/test/test_funnel_step_builder_integration.py b/products/experiments/backend/hogql_queries/test/test_funnel_step_builder_integration.py
index 29fdd523af5b..176863fec0dc 100644
--- a/products/experiments/backend/hogql_queries/test/test_funnel_step_builder_integration.py
+++ b/products/experiments/backend/hogql_queries/test/test_funnel_step_builder_integration.py
@@ -12,7 +12,7 @@ from posthog.schema import ActionsNode, EventsNode, ExperimentDataWarehouseNode,
from posthog.hogql import ast
from posthog.hogql.parser import parse_expr
-from products.actions.backend.models import Action
+from products.actions.backend.facade.testing import create_action
from products.experiments.backend.hogql_queries.funnel_step_builder import FunnelStepBuilder
@@ -22,7 +22,7 @@ class TestFunnelStepBuilderIntegration(BaseTest):
def test_mixed_node_types_integration(self):
"""Test that FunnelStepBuilder handles mixed EventsNode and ActionsNode."""
# Create an action first
- action = Action.objects.create(team=self.team, name="Test Action")
+ action = create_action(team=self.team, name="Test Action")
series: list[EventsNode | ActionsNode | ExperimentDataWarehouseNode] = [
EventsNode(event="pageview"),
diff --git a/products/experiments/backend/metric_utils.py b/products/experiments/backend/metric_utils.py
index 204d1249b37c..3fd0a2e16808 100644
--- a/products/experiments/backend/metric_utils.py
+++ b/products/experiments/backend/metric_utils.py
@@ -2,11 +2,12 @@
import copy
import logging
+from collections.abc import Mapping
from typing import Any
from posthog.models.team.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_actions
def _get_source_name(source: object) -> str:
@@ -94,16 +95,20 @@ def refresh_action_names_in_metric(
if not action_ids:
return query
+ names: Mapping[int, str | None]
if actions_by_id is None:
# Fetch all actions in a single query
# Only include actions that still exist (not deleted)
- actions_by_id = {
- action.id: action.name for action in Action.objects.filter(id__in=action_ids, team=team, deleted=False)
+ names = {
+ action.id: action.name
+ for action in get_actions(action_ids=action_ids, team_id=team.pk, include_deleted=False)
}
+ else:
+ names = actions_by_id
# Update action names throughout the query
- # If an action was deleted, its ID won't be in actions_by_id and the old name will be preserved
- _update_action_names(query, actions_by_id)
+ # If an action was deleted, its ID won't be in names and the old name will be preserved
+ _update_action_names(query, names)
return query
except Exception as e:
@@ -149,7 +154,7 @@ def _collect_action_ids(obj: Any, action_ids: set[int]) -> None:
_collect_action_ids(item, action_ids)
-def _update_action_names(obj: Any, actions_by_id: dict[int, str]) -> None:
+def _update_action_names(obj: Any, actions_by_id: Mapping[int, str | None]) -> None:
"""Recursively update all ActionsNode name fields with current action names."""
if isinstance(obj, dict):
if obj.get("kind") == "ActionsNode" and "id" in obj:
@@ -224,7 +229,7 @@ def resolve_action_events(action_ids: set[int], team: Team) -> dict[int, set[str
return {}
return {
action.id: {event for event in action.get_step_events() if event}
- for action in Action.objects.filter(id__in=action_ids, team=team, deleted=False)
+ for action in get_actions(action_ids=action_ids, team_id=team.pk, include_deleted=False)
}
diff --git a/products/experiments/backend/metric_validation.py b/products/experiments/backend/metric_validation.py
index 3a707648aedd..1830c0caee6a 100644
--- a/products/experiments/backend/metric_validation.py
+++ b/products/experiments/backend/metric_validation.py
@@ -30,7 +30,7 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from products.access_control.backend.facade.user_access_control import UserAccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_actions
from products.event_definitions.backend.models import EventDefinition, effective_project_id_expr
from products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_math
from products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidator
@@ -298,8 +298,7 @@ def validate_metric_action_ids(
if not action_ids:
return
- referenced = Action.objects.filter(id__in=action_ids, team_id=team.id)
- actions = list(referenced.filter(deleted=False) if require_existing else referenced)
+ actions = get_actions(action_ids=action_ids, team_id=team.id, include_deleted=not require_existing)
missing = action_ids - {action.id for action in actions}
if require_existing and missing:
missing_str = ", ".join(str(aid) for aid in sorted(missing))
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index c6bfb2de3a8e..08e866a7eea6 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -36,7 +36,7 @@ from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.team.extensions import get_or_create_team_extension
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.approvals.backend.exceptions import ApprovalRequired
from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
from products.cohorts.backend.models.cohort import Cohort
@@ -7065,7 +7065,7 @@ class TestExperimentService(APIBaseTest):
def test_metric_with_action_belonging_to_other_team_raises(self):
other_team = Team.objects.create(organization=self.organization, name="Other Team")
- action = Action.objects.create(team=other_team, name="other team action")
+ action = create_action(team=other_team, name="other team action")
service = self._service()
with self.assertRaises(ValidationError):
service.create_experiment(
@@ -7081,7 +7081,7 @@ class TestExperimentService(APIBaseTest):
)
def test_metric_with_deleted_action_raises(self):
- action = Action.objects.create(team=self.team, name="deleted action", deleted=True)
+ action = create_action(team=self.team, name="deleted action", deleted=True)
service = self._service()
with self.assertRaises(ValidationError):
service.create_experiment(
@@ -7097,7 +7097,7 @@ class TestExperimentService(APIBaseTest):
)
def test_metric_with_valid_action_id_passes(self):
- action = Action.objects.create(team=self.team, name="valid action")
+ action = create_action(team=self.team, name="valid action")
service = self._service()
experiment = service.create_experiment(
name="Valid Action",
@@ -7113,7 +7113,7 @@ class TestExperimentService(APIBaseTest):
assert experiment.metrics is not None and len(experiment.metrics) == 1
def test_update_with_deleted_action_still_referenced_succeeds(self):
- action = Action.objects.create(team=self.team, name="soon deleted action")
+ action = create_action(team=self.team, name="soon deleted action")
stale = {
"kind": "ExperimentMetric",
"metric_type": "mean",
@@ -7125,15 +7125,14 @@ class TestExperimentService(APIBaseTest):
feature_flag_key="stale-action-resend-flag",
metrics=[stale],
)
- action.deleted = True
- action.save()
+ update_action(action, deleted=True)
updated = service.update_experiment(experiment, {"metrics": [stale], "metrics_secondary": []})
assert updated.metrics is not None and len(updated.metrics) == 1
def test_update_rejects_new_unknown_action_alongside_resent_stale_one(self):
- action = Action.objects.create(team=self.team, name="another soon deleted action")
+ action = create_action(team=self.team, name="another soon deleted action")
stale = {
"kind": "ExperimentMetric",
"metric_type": "mean",
@@ -7145,8 +7144,7 @@ class TestExperimentService(APIBaseTest):
feature_flag_key="unknown-alongside-stale-action-flag",
metrics=[stale],
)
- action.deleted = True
- action.save()
+ update_action(action, deleted=True)
fresh = {
"kind": "ExperimentMetric",
"metric_type": "mean",
@@ -7163,7 +7161,7 @@ class TestExperimentService(APIBaseTest):
"products.access_control.backend.facade.user_access_control.UserAccessControl.access_controls_supported", True
)
def test_metric_action_needs_viewer_access_unless_already_referenced(self, placement: str):
- action = Action.objects.create(team=self.team, name="restricted action", created_by=self.user)
+ action = create_action(team=self.team, name="restricted action", created_by=self.user)
AccessControl.objects.create(team=self.team, resource="action", resource_id=str(action.id), access_level="none")
metric = {"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "ActionsNode", "id": action.id}}
definition: dict = {"metrics": [metric], "metrics_secondary": []}
@@ -7265,7 +7263,7 @@ class TestExperimentService(APIBaseTest):
assert experiment.metrics[0]["metric_type"] == "funnel"
def test_funnel_metric_with_nonexistent_action_in_series_raises(self):
- action = Action.objects.create(team=self.team, name="real action")
+ action = create_action(team=self.team, name="real action")
service = self._service()
with self.assertRaises(ValidationError):
service.create_experiment(
@@ -7595,7 +7593,7 @@ class TestExperimentService(APIBaseTest):
assert experiment.metrics is not None and len(experiment.metrics) == 1
def test_action_nodes_not_checked_for_event_existence(self):
- action = Action.objects.create(team=self.team, name="valid action for event test")
+ action = create_action(team=self.team, name="valid action for event test")
service = self._service()
experiment = service.create_experiment(
name="Action No Event Check",
diff --git a/products/experiments/backend/test/test_metric_events.py b/products/experiments/backend/test/test_metric_events.py
index 24893e278584..0ce29577ad65 100644
--- a/products/experiments/backend/test/test_metric_events.py
+++ b/products/experiments/backend/test/test_metric_events.py
@@ -11,7 +11,7 @@ from posthog.schema import ActionsNode, EventsNode
from posthog.models import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.experiments.backend.metric_events import (
MetricHit,
MetricSourceRole,
@@ -174,9 +174,9 @@ class TestResolveMetricEvents(MetricEventsTestMixin):
assert sources[0].metric_name == expected_title
def test_resolves_action_source(self) -> None:
- action = Action.objects.create(team=self.team, name="Purchased", steps_json=[{"event": "purchase"}])
+ action = create_action(team=self.team, name="Purchased", steps_json=[{"event": "purchase"}])
experiment = self._experiment(
- metrics=[_metric("mean", source={"kind": "ActionsNode", "id": action.pk})],
+ metrics=[_metric("mean", source={"kind": "ActionsNode", "id": action.id})],
)
sources = resolve_metric_events(experiment)
@@ -185,7 +185,7 @@ class TestResolveMetricEvents(MetricEventsTestMixin):
assert len(sources[0].sources) == 1
node = sources[0].sources[0].node
assert isinstance(node, ActionsNode)
- assert int(node.id) == action.pk
+ assert int(node.id) == action.id
assert sources[0].session_linkable is True
def test_data_warehouse_only_metric_is_not_session_linkable(self) -> None:
diff --git a/products/experiments/backend/test/test_metric_utils.py b/products/experiments/backend/test/test_metric_utils.py
index 7e599762ab92..ff5756a1fedc 100644
--- a/products/experiments/backend/test/test_metric_utils.py
+++ b/products/experiments/backend/test/test_metric_utils.py
@@ -6,7 +6,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.experiments.backend.metric_utils import (
collect_metric_events_and_action_ids,
collect_metric_warehouse_tables,
@@ -21,9 +21,9 @@ class TestRefreshActionNamesInMetric(BaseTest):
def setUp(self):
super().setUp()
# Create test actions
- self.action1 = Action.objects.create(team=self.team, name="Original Action 1")
- self.action2 = Action.objects.create(team=self.team, name="Original Action 2")
- self.action3 = Action.objects.create(team=self.team, name="Original Action 3")
+ self.action1 = create_action(team=self.team, name="Original Action 1")
+ self.action2 = create_action(team=self.team, name="Original Action 2")
+ self.action3 = create_action(team=self.team, name="Original Action 3")
def test_refresh_action_names_in_mean_metric(self):
"""Test refreshing action names in a mean metric."""
@@ -38,8 +38,7 @@ class TestRefreshActionNamesInMetric(BaseTest):
}
# Rename the action
- self.action1.name = "Renamed Action 1"
- self.action1.save()
+ update_action(self.action1, name="Renamed Action 1")
# Refresh action names
updated_query = refresh_action_names_in_metric(query, self.team)
@@ -75,10 +74,8 @@ class TestRefreshActionNamesInMetric(BaseTest):
}
# Rename both actions
- self.action1.name = "Renamed Action 1"
- self.action1.save()
- self.action2.name = "Renamed Action 2"
- self.action2.save()
+ update_action(self.action1, name="Renamed Action 1")
+ update_action(self.action2, name="Renamed Action 2")
# Refresh action names
updated_query = refresh_action_names_in_metric(query, self.team)
@@ -113,10 +110,8 @@ class TestRefreshActionNamesInMetric(BaseTest):
}
# Rename the actions
- self.action1.name = "Renamed Action 1"
- self.action1.save()
- self.action2.name = "Renamed Action 2"
- self.action2.save()
+ update_action(self.action1, name="Renamed Action 1")
+ update_action(self.action2, name="Renamed Action 2")
# Refresh action names
updated_query = refresh_action_names_in_metric(query, self.team)
@@ -155,8 +150,7 @@ class TestRefreshActionNamesInMetric(BaseTest):
"""Test that missing or deleted actions don't cause errors."""
if action_exists:
action_id = self.action1.id
- self.action1.deleted = True
- self.action1.save()
+ update_action(self.action1, deleted=True)
else:
action_id = 99999
@@ -213,8 +207,7 @@ class TestRefreshActionNamesInMetric(BaseTest):
}
# Rename the action
- self.action1.name = "Renamed Action 1"
- self.action1.save()
+ update_action(self.action1, name="Renamed Action 1")
# Store original name
original_name = original_query["source"]["name"]
@@ -252,8 +245,7 @@ class TestRefreshActionNamesInMetric(BaseTest):
}
# Rename the action
- self.action1.name = "Renamed Action 1"
- self.action1.save()
+ update_action(self.action1, name="Renamed Action 1")
# Refresh action names
updated_query = refresh_action_names_in_metric(query, self.team)
@@ -279,12 +271,9 @@ class TestRefreshActionNamesInMetric(BaseTest):
}
# Rename all actions
- self.action1.name = "Renamed Action 1"
- self.action1.save()
- self.action2.name = "Renamed Action 2"
- self.action2.save()
- self.action3.name = "Renamed Action 3"
- self.action3.save()
+ update_action(self.action1, name="Renamed Action 1")
+ update_action(self.action2, name="Renamed Action 2")
+ update_action(self.action3, name="Renamed Action 3")
# Count queries executed
with self.assertNumQueries(1): # Should be a single query to fetch all actions
@@ -477,7 +466,7 @@ class TestCollectMetricWarehouseTables(SimpleTestCase):
class TestResolveActionEvents(BaseTest):
def test_resolves_actions_to_their_step_events(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Signed up",
steps_json=[{"event": "signup"}, {"event": "$autocapture"}],
@@ -485,12 +474,12 @@ class TestResolveActionEvents(BaseTest):
assert resolve_action_events({action.id}, self.team) == {action.id: {"signup", "$autocapture"}}
def test_ignores_deleted_actions(self):
- action = Action.objects.create(team=self.team, name="Gone", steps_json=[{"event": "ghost"}], deleted=True)
+ action = create_action(team=self.team, name="Gone", steps_json=[{"event": "ghost"}], deleted=True)
assert resolve_action_events({action.id}, self.team) == {}
def test_batches_into_single_query(self):
- action_a = Action.objects.create(team=self.team, name="A", steps_json=[{"event": "a1"}, {"event": "a2"}])
- action_b = Action.objects.create(team=self.team, name="B", steps_json=[{"event": "b1"}])
+ action_a = create_action(team=self.team, name="A", steps_json=[{"event": "a1"}, {"event": "a2"}])
+ action_b = create_action(team=self.team, name="B", steps_json=[{"event": "b1"}])
with self.assertNumQueries(1):
resolved = resolve_action_events({action_a.id, action_b.id}, self.team)
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 7ef9c5097195..058a2937b26d 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -42,7 +42,8 @@ from posthog.test.test_journeys import journeys_for
from products.access_control.backend.facade.api import upsert_property_access_control
from products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInput
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.experiments.backend.experiment_service import ExperimentService
@@ -389,7 +390,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertEqual(response.json()["results"][0]["id"], purchase_experiment.id)
def test_filter_by_event_resolves_actions(self) -> None:
- action = Action.objects.create(team=self.team, name="Checked out", steps_json=[{"event": "checkout"}])
+ action = create_action(team=self.team, name="Checked out", steps_json=[{"event": "checkout"}])
flag = FeatureFlag.objects.create(
team=self.team,
created_by=self.user,
@@ -574,7 +575,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertTrue(all(fingerprints))
def _create_experiment_with_action_metrics(self, index: int) -> tuple[Experiment, Action]:
- action = Action.objects.create(team=self.team, name=f"Action {index}", steps_json=[{"event": f"event_{index}"}])
+ action = create_action(team=self.team, name=f"Action {index}", steps_json=[{"event": f"event_{index}"}])
flag = FeatureFlag.objects.create(team=self.team, key=f"action-metric-flag-{index}", created_by=self.user)
experiment = Experiment.objects.create(
team=self.team,
@@ -1283,8 +1284,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
# Action-name refresh lives on the detail response — the list endpoint no longer
# returns metrics (see ExperimentBasicSerializer).
experiment, action = self._create_experiment_with_action_metrics(0)
- action.name = "Renamed action"
- action.save()
+ update_action(action, name="Renamed action")
response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment.id}")
self.assertEqual(response.status_code, status.HTTP_200_OK)
@@ -1851,7 +1851,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
the saved query with the link overrides applied, the same dict the daily workflow files its rows
under, or the chart reads an empty series for an override-configured saved metric."""
breakdowns = [{"type": "event", "property": "$os_name"}] if link_has_breakdowns else []
- action = Action.objects.create(team=self.team, name="Stored name", steps_json=[{"event": "$pageview"}])
+ action = create_action(team=self.team, name="Stored name", steps_json=[{"event": "$pageview"}])
source = (
{"kind": "ActionsNode", "id": action.id, "name": action.name}
if rename_action
@@ -1865,7 +1865,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
},
)
if rename_action:
- Action.objects.filter(pk=action.pk).update(name="Current name")
+ update_action(action, name="Current name")
metadata = {"type": "primary", "breakdowns": breakdowns, "breakdown_limit": 20}
experiment_response = self.client.post(
f"/api/projects/{self.team.id}/experiments/",
@@ -4414,7 +4414,7 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
def test_update_experiment_exposure_config_with_action(self):
# Create an action
- action = Action.objects.create(
+ action = create_action(
name="Test Action",
team=self.team,
steps_json=[{"event": "purchase", "properties": [{"key": "plan", "value": "premium", "type": "event"}]}],
@@ -7706,7 +7706,7 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe
name="cohort_X",
)
- action1 = Action.objects.create(
+ action1 = create_action(
team=self.team,
name="action1",
steps_json=[
diff --git a/products/experiments/backend/test/test_session_buckets_api.py b/products/experiments/backend/test/test_session_buckets_api.py
index 7b68fea8b7bf..b371a2e67fd5 100644
--- a/products/experiments/backend/test/test_session_buckets_api.py
+++ b/products/experiments/backend/test/test_session_buckets_api.py
@@ -21,7 +21,7 @@ from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.experiments.backend import session_buckets
from products.experiments.backend.hogql_queries.exposure_query_logic import (
EXPERIMENT_EXPOSURE_EVENT,
@@ -362,11 +362,11 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
assert expected_reason in response.json()["detail"]
def test_funnel_dropoff_completion_check_survives_an_action_step(self) -> None:
- action = Action.objects.create(team=self.team, name="Viewed cart", steps_json=[{"event": "cart viewed"}])
+ action = create_action(team=self.team, name="Viewed cart", steps_json=[{"event": "cart viewed"}])
metric = _funnel(
"a7777777-7777-7777-7777-777777777777",
"Checkout via action",
- [CART, {"kind": "ActionsNode", "id": action.pk}, SERVER_CHARGE],
+ [CART, {"kind": "ActionsNode", "id": action.id}, SERVER_CHARGE],
)
experiment = self._create_experiment(metrics=[metric])
self._session(events=[("cart viewed", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])
@@ -620,8 +620,8 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
@parameterized.expand([("custom_event",), ("action",)])
def test_session_linkable_custom_exposure_defines_the_population(self, exposure_kind: str) -> None:
if exposure_kind == "action":
- action = Action.objects.create(team=self.team, name="Checkout", steps_json=[{"event": "checkout started"}])
- exposure_config: dict[str, Any] = {"kind": "ActionsNode", "id": action.pk}
+ action = create_action(team=self.team, name="Checkout", steps_json=[{"event": "checkout started"}])
+ exposure_config: dict[str, Any] = {"kind": "ActionsNode", "id": action.id}
else:
exposure_config = {
"kind": "ExperimentEventExposureConfig",
@@ -650,13 +650,13 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
assert response.json()["used_exposure_fallback"] is False
def test_action_metrics_are_not_excluded_by_the_linkability_check(self) -> None:
- action = Action.objects.create(team=self.team, name="Purchased", steps_json=[{"event": "purchase"}])
+ action = create_action(team=self.team, name="Purchased", steps_json=[{"event": "purchase"}])
action_metric = {
"kind": "ExperimentMetric",
"metric_type": "mean",
"uuid": "88888888-8888-8888-8888-888888888888",
"name": "Purchased (action)",
- "source": {"kind": "ActionsNode", "id": action.pk},
+ "source": {"kind": "ActionsNode", "id": action.id},
}
experiment = self._create_experiment(metrics=[action_metric])
purchased = self._session(events=[("purchase", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])
diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.py
index 928b5a1568ce..d00e9d5dc915 100644
--- a/products/experiments/backend/test/test_session_context_api.py
+++ b/products/experiments/backend/test/test_session_context_api.py
@@ -28,7 +28,7 @@ from posthog.session_recordings.queries.test.session_replay_sql import produce_r
from products.access_control.backend.facade.api import upsert_property_access_control
from products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInput
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric
from products.experiments.backend.session_context import (
@@ -724,9 +724,9 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):
def test_action_exposure_criteria_defines_exposure_timestamp(self) -> None:
self._create_recording()
- action = Action.objects.create(team=self.team, name="Purchased", steps_json=[{"event": "purchase"}])
+ action = create_action(team=self.team, name="Purchased", steps_json=[{"event": "purchase"}])
self._create_experiment(
- exposure_criteria={"exposure_config": {"kind": "ActionsNode", "id": action.pk}},
+ exposure_criteria={"exposure_config": {"kind": "ActionsNode", "id": action.id}},
)
self._create_session_event(
event="purchase",
diff --git a/products/experiments/backend/test/test_session_event_deltas_api.py b/products/experiments/backend/test/test_session_event_deltas_api.py
index fbd4ae46c8a4..0301ef8ea32c 100644
--- a/products/experiments/backend/test/test_session_event_deltas_api.py
+++ b/products/experiments/backend/test/test_session_event_deltas_api.py
@@ -17,7 +17,7 @@ from posthog.models.utils import uuid7
from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.experiments.backend import session_event_deltas
from products.experiments.backend.hogql_queries.experiment_exposure_query_builder import ExposureQueryBuilder
from products.experiments.backend.models.experiment import Experiment
@@ -1073,9 +1073,7 @@ class TestExperimentSessionEventDeltas(ClickhouseTestMixin, APILicensedTest):
@rank_anything
def test_an_action_based_exposure_still_backs_its_cards_with_recordings(self) -> None:
- action = Action.objects.create(
- team=self.team, name="Reached checkout", steps_json=[{"event": "checkout_viewed"}]
- )
+ action = create_action(team=self.team, name="Reached checkout", steps_json=[{"event": "checkout_viewed"}])
experiment = self._create_experiment(
metrics=[PURCHASE_METRIC], exposure_criteria={"exposure_config": {"kind": "ActionsNode", "id": action.id}}
)
diff --git a/products/experiments/backend/test/test_setup_context.py b/products/experiments/backend/test/test_setup_context.py
index 6316c5e53a34..b4b21d7b40d0 100644
--- a/products/experiments/backend/test/test_setup_context.py
+++ b/products/experiments/backend/test/test_setup_context.py
@@ -18,7 +18,7 @@ from parameterized import parameterized
from posthog.exceptions import ClickHouseQueryTimeOut
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.experiments.backend import setup_context as setup_context_module
from products.experiments.backend.hogql_queries.exposure_query_logic import (
DEFAULT_EXPOSURE_EVENT,
@@ -993,7 +993,7 @@ class TestPostgresSections(APIBaseTest):
assert previous.summary.using_uneven_split == 0
def test_an_action_exposure_is_reported_as_an_action(self) -> None:
- action = Action.objects.create(team=self.team, name="Saw pricing", steps_json=[{"event": "$pageview"}])
+ action = create_action(team=self.team, name="Saw pricing", steps_json=[{"event": "$pageview"}])
self._experiment(
"action-exposure", exposure_criteria={"exposure_config": {"kind": "ActionsNode", "id": action.id}}
)
@@ -1138,7 +1138,7 @@ class TestPostgresSections(APIBaseTest):
popular = self._saved_metric("Popular", _mean_metric("popular", event="signup"))
inflated = self._saved_metric("Inflated by deleted", _mean_metric("inflated", event="signup"))
- action = Action.objects.create(team=self.team, name="Bought", steps_json=[{"event": "purchase"}])
+ action = create_action(team=self.team, name="Bought", steps_json=[{"event": "purchase"}])
via_action = self._saved_metric(
"Via action",
{
diff --git a/products/exports/backend/tasks/test/test_csv_exporter.py b/products/exports/backend/tasks/test/test_csv_exporter.py
index 83e6cd1b95f1..af346219eeba 100644
--- a/products/exports/backend/tasks/test/test_csv_exporter.py
+++ b/products/exports/backend/tasks/test/test_csv_exporter.py
@@ -38,7 +38,7 @@ from posthog.storage.object_storage import ObjectStorageError
from posthog.test.test_journeys import journeys_for
from posthog.utils import absolute_uri
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.exports.backend.models.exported_asset import ExportedAsset
from products.exports.backend.source_authentication import assert_export_authorization
from products.exports.backend.tasks import csv_exporter
@@ -1454,7 +1454,7 @@ class TestCSVExporter(APIBaseTest):
_create_person(distinct_ids=["user_1"], team=self.team)
_create_person(distinct_ids=["user_2"], team=self.team)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Test Action",
steps_json=[{"event": "test_action_event"}],
diff --git a/products/marketing_analytics/backend/demo/config.py b/products/marketing_analytics/backend/demo/config.py
index 0ff49796b4e4..b875fa47734b 100644
--- a/products/marketing_analytics/backend/demo/config.py
+++ b/products/marketing_analytics/backend/demo/config.py
@@ -2,7 +2,8 @@
from posthog.models import Team, User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import create_action, find_actions_by_name
+from products.actions.backend.facade.contracts import Action
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.marketing_analytics.backend.demo.warehouse import STRIPE_INVOICES_TABLE
from products.marketing_analytics.backend.demo.world import EVENT_DEMO_BOOKED, EVENT_PURCHASE, EVENT_SIGNUP
@@ -30,10 +31,10 @@ _DEFAULT_SCHEMA_MAP = {
def _ensure_demo_action(team: Team) -> Action:
- action = Action.objects.filter(team=team, name="Demo booked (marketing demo)", deleted=False).first()
- if action:
- return action
- return Action.objects.create(
+ existing = find_actions_by_name(team_id=team.pk, name="Demo booked (marketing demo)")
+ if existing:
+ return existing[0]
+ return create_action(
team=team,
name="Demo booked (marketing demo)",
steps_json=[{"event": EVENT_DEMO_BOOKED}],
@@ -66,7 +67,7 @@ def build_conversion_goals(team: Team) -> list[dict]:
},
{
"kind": "ActionsNode",
- "id": action.pk,
+ "id": action.id,
"conversion_goal_id": "cg_demos",
"name": "Demo booked (marketing demo)",
"conversion_goal_name": "Demos booked",
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py
index ee719b16395f..d719596db189 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_conditions.py
@@ -15,7 +15,8 @@ from posthog.hogql.property import action_to_expr, property_to_expr
from posthog.models import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
ConversionGoal = ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3
@@ -50,8 +51,8 @@ def action_match_expr(conversion_goal: ConversionGoal, team: Team) -> Optional[a
if not isinstance(conversion_goal, ConversionGoalFilter2) or not conversion_goal.id:
return None
try:
- action = Action.objects.get(pk=int(conversion_goal.id), team__project_id=team.project_id)
- except (Action.DoesNotExist, TypeError, ValueError):
+ action = get_action(action_id=int(conversion_goal.id), project_id=team.project_id)
+ except (ActionNotFound, TypeError, ValueError):
return None
return action_to_expr(action)
@@ -61,8 +62,8 @@ def action_property_keys(conversion_goal: ConversionGoal, team: Team) -> list[st
if not isinstance(conversion_goal, ConversionGoalFilter2) or not conversion_goal.id:
return []
try:
- action = Action.objects.get(pk=int(conversion_goal.id), team__project_id=team.project_id)
- except (Action.DoesNotExist, TypeError, ValueError):
+ action = get_action(action_id=int(conversion_goal.id), project_id=team.project_id)
+ except (ActionNotFound, TypeError, ValueError):
return []
return [prop["key"] for step in action.steps for prop in step.properties or [] if prop.get("key")]
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
index de4e5740c250..76dcf6829e43 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_table_query_runner.py
@@ -28,7 +28,7 @@ from posthog.models.team.team_marketing_analytics_config import MAX_ATTRIBUTION_
from posthog.models.utils import uuid7
from posthog.test.persons import create_person
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.marketing_analytics.backend.hogql_queries.attribution_table_query_runner import (
MarketingAnalyticsAttributionQueryRunner,
@@ -804,12 +804,12 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
# The action branch resolves the goal through Postgres and `action_to_expr` rather than a plain
# event name. A goal that silently matched nothing would render an empty table that reads as an
# honest absence of conversions.
- action = Action.objects.create(team=self.team, name="Purchased", steps_json=[{"event": CONVERSION_EVENT}])
+ action = create_action(team=self.team, name="Purchased", steps_json=[{"event": CONVERSION_EVENT}])
config = self.team.marketing_analytics_config
config.conversion_goals = [
ConversionGoalFilter2(
kind="ActionsNode",
- id=str(action.pk),
+ id=str(action.id),
name="Purchased",
conversion_goal_id=GOAL_ID,
conversion_goal_name="Purchased",
@@ -936,7 +936,7 @@ class TestMarketingAnalyticsAttributionQueryRunner(ClickhouseTestMixin, BaseTest
self.assertAlmostEqual(by_campaign["a"][AttributionMode.LAST_TOUCH], 1.0, places=4)
def test_action_goal_whose_action_is_gone_reports_the_misconfiguration(self):
- # An unresolvable action used to raise Action.DoesNotExist out of query building, so a goal
+ # An unresolvable action used to raise out of query building, so a goal
# pointing at a deleted action 500d instead of telling the user to fix the goal.
config = self.team.marketing_analytics_config
config.conversion_goals = [
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 f7cb565ed771..e01714aba10c 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,7 +28,7 @@ from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.models.event.util import bulk_create_events
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.marketing_analytics.backend.hogql_queries.conversion_goal_conditions import (
add_conversion_goal_property_filters,
)
@@ -43,7 +43,7 @@ def _create_action(**kwargs):
name = kwargs.pop("name")
event_name = kwargs.pop("event_name", name)
properties = kwargs.pop("properties", {})
- action = Action.objects.create(team=team, name=name, steps_json=[{"event": event_name, "properties": properties}])
+ action = create_action(team=team, name=name, steps_json=[{"event": event_name, "properties": properties}])
return action
@@ -221,7 +221,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
goal = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="actions_basic",
conversion_goal_name="Actions Basic",
math=BaseMathType.TOTAL,
@@ -1687,7 +1687,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
goal = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="integration_actions",
conversion_goal_name="Integration Actions",
math=BaseMathType.TOTAL,
@@ -4947,13 +4947,13 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Create action with multiple events
- action = Action.objects.create(
+ action = create_action(
team=self.team, name="User Conversion", steps_json=[{"event": "sign_up"}, {"event": "activate_account"}]
)
goal = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="multi_events_total",
conversion_goal_name="Multi Events Total",
math=BaseMathType.TOTAL,
@@ -5050,7 +5050,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Create action with multiple events
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="User Conversion Steps",
steps_json=[{"event": "sign_up"}, {"event": "activate_account"}],
@@ -5059,7 +5059,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
# Test with TOTAL math
goal_total = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="multi_users_total",
conversion_goal_name="Multi Users Total",
math=BaseMathType.TOTAL,
@@ -5089,7 +5089,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
# Test with DAU math
goal_dau = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="multi_users_dau",
conversion_goal_name="Multi Users DAU",
math=BaseMathType.DAU,
@@ -5174,7 +5174,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Create action with multiple events and property filters
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Filtered User Conversion",
steps_json=[
@@ -5188,7 +5188,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
goal = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="filtered_multi_events",
conversion_goal_name="Filtered Multi Events",
math=BaseMathType.TOTAL,
@@ -5247,13 +5247,13 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Create action with 2 events
- action_both_events = Action.objects.create(
+ action_both_events = create_action(
team=self.team, name="Two Event Action", steps_json=[{"event": "sign_up"}, {"event": "activate_account"}]
)
goal = ConversionGoalFilter2(
kind="ActionsNode",
- id=action_both_events.pk,
+ id=action_both_events.id,
conversion_goal_id="semantics_test",
conversion_goal_name="Semantics Test",
math=BaseMathType.TOTAL,
@@ -5311,11 +5311,11 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
_create_event(distinct_id="attribution_test_user", event="sign_up", team=self.team)
flush_persons_and_events_in_batches()
- action = Action.objects.create(team=self.team, name="Sign Up Action", steps_json=[{"event": "sign_up"}])
+ action = create_action(team=self.team, name="Sign Up Action", steps_json=[{"event": "sign_up"}])
goal = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="attribution_test",
conversion_goal_name="Attribution Test",
math=BaseMathType.TOTAL,
@@ -5376,7 +5376,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
flush_persons_and_events_in_batches()
# Create multi-event action
- action = Action.objects.create(
+ action = create_action(
team=self.team, name="User Onboarding", steps_json=[{"event": "sign_up"}, {"event": "activate_account"}]
)
@@ -5394,7 +5394,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
actions_goal = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="actions_test",
conversion_goal_name="Actions Test",
math=BaseMathType.TOTAL,
@@ -5478,7 +5478,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
goal = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="signup_test",
conversion_goal_name="Signup Test",
math=BaseMathType.TOTAL,
@@ -6199,7 +6199,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
_create_event(distinct_id="mt_action_user", event="sign_up", team=self.team)
flush_persons_and_events_in_batches()
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Signup Flow",
steps_json=[{"event": "sign_up"}, {"event": "activate_account"}],
@@ -6207,7 +6207,7 @@ class TestConversionGoalProcessor(ClickhouseTestMixin, BaseTest):
goal = ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id="mt_actions_linear",
conversion_goal_name="Multi Touch Actions Linear",
math=BaseMathType.TOTAL,
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
index 341d8a71d537..a3b2a914d334 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
@@ -25,7 +25,7 @@ from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.models import PropertyDefinition
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import ConversionGoalProcessor
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig
@@ -217,7 +217,7 @@ class TestConversionGoalProcessorRefactor(BaseTest):
def test_action_step_on_revenue_property_is_not_precomputable(self):
# An action goal pulls its steps' filters into the INSERT, so they must be checked too.
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Paying purchase",
steps_json=[
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 826131dd0e7a..b7a428203909 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
@@ -24,7 +24,7 @@ from posthog.clickhouse.client.execute import sync_execute
from posthog.clickhouse.preaggregation.marketing_touchpoints_sql import TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
LazyComputationResult,
LazyComputationTable,
@@ -127,7 +127,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):
def _create_test_action_goal(self, action: Action, goal_id: str, goal_name: str) -> ConversionGoalFilter2:
return ConversionGoalFilter2(
kind="ActionsNode",
- id=action.pk,
+ id=action.id,
conversion_goal_id=goal_id,
conversion_goal_name=goal_name,
math=BaseMathType.TOTAL,
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 4726fca399df..fe9681a96af9 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
@@ -22,7 +22,8 @@ from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.models.team.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_table_query_runner import (
MarketingAnalyticsTableQueryRunner,
)
@@ -103,7 +104,7 @@ class DataConfig:
def _create_action(team, name: str = "test_action") -> Action:
- return Action.objects.create(
+ return create_action(
team=team,
name=name,
steps_json=[{"event": "test_event"}],
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 7ed1d7418e88..dac40082624d 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
@@ -25,7 +25,8 @@ from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.models.team.team import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_table_query_runner import (
MarketingAnalyticsTableQueryRunner,
)
@@ -107,7 +108,7 @@ class DataConfig:
def _create_action(team, name: str = "test_action") -> Action:
- return Action.objects.create(
+ return create_action(
team=team,
name=name,
steps_json=[{"event": "test_event"}],
diff --git a/products/marketing_analytics/backend/services/conversion_goals_inspector.py b/products/marketing_analytics/backend/services/conversion_goals_inspector.py
index 1246fee39424..8bb959e3898d 100644
--- a/products/marketing_analytics/backend/services/conversion_goals_inspector.py
+++ b/products/marketing_analytics/backend/services/conversion_goals_inspector.py
@@ -30,7 +30,8 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.sync import database_sync_to_async
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import Action, ActionNotFound
from products.marketing_analytics.backend.services.native_integrations import (
NativeIntegration,
build_combined_alias_map,
@@ -457,8 +458,8 @@ def _resolve_action(team: Team, goal_id: str) -> tuple[Action | None, str | None
except (TypeError, ValueError):
return None, f"Goal id '{goal_id}' is not a valid integer for ActionsNode"
try:
- return Action.objects.get(id=action_id_int, team_id=team.pk, deleted=False), None
- except Action.DoesNotExist:
+ return get_action(action_id=action_id_int, team_id=team.pk, include_deleted=False), None
+ except ActionNotFound:
return None, f"Action {goal_id} does not exist or is deleted"
diff --git a/products/marketing_analytics/backend/services/conversion_recommendations.py b/products/marketing_analytics/backend/services/conversion_recommendations.py
index 444f12184326..ec7540525558 100644
--- a/products/marketing_analytics/backend/services/conversion_recommendations.py
+++ b/products/marketing_analytics/backend/services/conversion_recommendations.py
@@ -21,7 +21,7 @@ from posthog.taxonomy.property_access import restricted_property_names
from posthog.user_permissions import UserPermissions
from products.access_control.backend.facade.user_access_control import UserAccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade import api as actions_facade
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.event_definitions.backend.models.event_property import EventProperty
from products.event_definitions.backend.models.property_definition import PropertyDefinition, effective_project_id_expr
@@ -320,26 +320,23 @@ class ConversionRecommendationService:
self.require_generation_access()
goals = self.configured_goals()
configured = {goal.source_ref for goal in goals}
- alias = definition_read_db_alias(Action)
+ alias = actions_facade.action_read_db_alias()
with statement_timeout(alias, CATALOG_QUERY_TIMEOUT_MS, DefinitionListTimedOut, CATALOG_QUERY_TIMEOUTS):
- actions = list(
- UserAccessControl(self.user, team=self.team)
- .filter_queryset_by_access_level(
- Action.objects.using(alias).filter(team_id=self.team.pk, deleted=False), resource="action"
- )
- .annotate(short_description=Substr("description", 1, 200))
- .order_by("-updated_at", "-pk")
- .values_list("pk", "name", "short_description")[:MAX_CATALOG_ACTIONS]
+ actions = actions_facade.list_action_catalog(
+ team_id=self.team.pk,
+ access_control=UserAccessControl(self.user, team=self.team),
+ limit=MAX_CATALOG_ACTIONS,
+ using=alias,
)
sources = [
ConversionCandidate(
- source_ref=f"action:{pk}",
+ source_ref=f"action:{action.id}",
kind="ActionsNode",
- action_id=pk,
- name=name or f"Action {pk}",
- description=description or "",
+ action_id=action.id,
+ name=action.name or f"Action {action.id}",
+ description=action.short_description or "",
)
- for pk, name, description in actions
+ for action in actions
] + self.event_catalog(run)
candidates: dict[str, ConversionCandidate] = {}
catalog: list[dict[str, str]] = []
@@ -382,12 +379,8 @@ class ConversionRecommendationService:
action_ids = [
int(goal["id"]) for goal in goals if goal.get("kind") == "ActionsNode" and str(goal.get("id", "")).isdigit()
]
- accessible_action_ids = set(
- UserAccessControl(self.user, team=self.team)
- .filter_queryset_by_access_level(
- Action.objects.filter(team_id=self.team.pk, pk__in=action_ids, deleted=False), resource="action"
- )
- .values_list("pk", flat=True)
+ accessible_action_ids = actions_facade.accessible_action_ids(
+ team_id=self.team.pk, action_ids=action_ids, access_control=UserAccessControl(self.user, team=self.team)
)
summaries: list[ConfiguredConversionGoal] = []
for goal in goals:
@@ -570,12 +563,8 @@ class ConversionRecommendationService:
for item in result.recommendations
if item.candidate.kind == "ActionsNode" and item.candidate.action_id is not None
]
- allowed = set(
- UserAccessControl(self.user, team=self.team)
- .filter_queryset_by_access_level(
- Action.objects.filter(team_id=self.team.pk, deleted=False, pk__in=action_ids), resource="action"
- )
- .values_list("id", flat=True)
+ allowed = actions_facade.accessible_action_ids(
+ team_id=self.team.pk, action_ids=action_ids, access_control=UserAccessControl(self.user, team=self.team)
)
return result.model_copy(
update={
diff --git a/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py b/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py
index 751b7ef0ca42..954104e2c152 100644
--- a/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py
+++ b/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py
@@ -8,7 +8,7 @@ from django.utils import timezone
from posthog.schema import DateRange
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import acreate_action, create_action
from products.marketing_analytics.backend.services.conversion_goals_inspector import (
UtmSplitCounts,
explain_conversion_goal,
@@ -317,12 +317,12 @@ class TestResolveAction(APIBaseTest):
# Create a second team in a separate organization to ensure cross-team isolation.
other_org = await sync_to_async(Organization.objects.create)(name="Other Org")
other_team = await sync_to_async(Team.objects.create)(organization=other_org, name="Other Team")
- other_action = await sync_to_async(Action.objects.create)(team=other_team, name="Other Team Action")
+ other_action = await acreate_action(team=other_team, name="Other Team Action")
# _resolve_action scoped to self.team must NOT return an action that belongs
# to other_team — otherwise team A could read team B's action name and step
# events through the diagnostic tool.
- action, error = await _resolve_action(self.team, str(other_action.pk))
+ action, error = await _resolve_action(self.team, str(other_action.id))
assert action is None
assert error is not None
@@ -331,7 +331,7 @@ class TestResolveAction(APIBaseTest):
from products.marketing_analytics.backend.services.conversion_goals_inspector import _resolve_action
with patch(
- "products.marketing_analytics.backend.services.conversion_goals_inspector.Action.objects.get",
+ "products.marketing_analytics.backend.services.conversion_goals_inspector.get_action",
) as p_get:
action, error = await _resolve_action(self.team, "not-an-int")
assert action is None
@@ -670,7 +670,7 @@ class TestListActionGoalFiltersClickhouse(ClickhouseTestMixin, BaseTest):
def setUp(self) -> None:
super().setUp()
- self.action = Action.objects.create(
+ self.action = create_action(
team=self.team,
name="Pro purchase",
steps_json=[
diff --git a/products/marketing_analytics/backend/services/test_conversion_recordings.py b/products/marketing_analytics/backend/services/test_conversion_recordings.py
index e69e63c2547e..92b85ba7a69b 100644
--- a/products/marketing_analytics/backend/services/test_conversion_recordings.py
+++ b/products/marketing_analytics/backend/services/test_conversion_recordings.py
@@ -24,7 +24,7 @@ from posthog.clickhouse.preaggregation.marketing_conversions_sql import TRUNCATE
from posthog.clickhouse.preaggregation.marketing_touchpoints_sql import TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL
from posthog.clickhouse.query_tagging import get_query_tag_value, tags_context
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
from products.marketing_analytics.backend.hogql_queries.errors import MarketingPrecomputeNotReady
@@ -294,7 +294,7 @@ class TestConversionRecordings(ClickhouseTestMixin, APIBaseTest):
self.addCleanup(sync_execute, TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL())
self.addCleanup(sync_execute, TRUNCATE_MARKETING_CONVERSIONS_TABLE_SQL())
if action_goal:
- action = Action.objects.create(team=self.team, name="Purchases", steps_json=[{"event": "purchase"}])
+ action = create_action(team=self.team, name="Purchases", steps_json=[{"event": "purchase"}])
config = self.team.marketing_analytics_config
config.conversion_goals[0].update(kind="ActionsNode", id=action.id)
config.conversion_goals[0].pop("event")
diff --git a/products/marketing_analytics/backend/test_api_conversion_recommendations.py b/products/marketing_analytics/backend/test_api_conversion_recommendations.py
index 5d8ed710e368..856983684aaf 100644
--- a/products/marketing_analytics/backend/test_api_conversion_recommendations.py
+++ b/products/marketing_analytics/backend/test_api_conversion_recommendations.py
@@ -18,7 +18,7 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfig
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.event_definitions.backend.models.event_property import EventProperty
from products.event_definitions.backend.models.property_definition import PropertyDefinition
@@ -455,8 +455,8 @@ class TestConversionRecommendations(APIBaseTest):
EventDefinition.objects.create(team=self.team, name="$pageview", last_seen_at=now)
EventDefinition.objects.create(team=self.team, name="old_event", last_seen_at=now - timedelta(days=40))
EventDefinition.objects.create(team=self.team, name="activity_date_unknown")
- action = Action.objects.create(team=self.team, name="Accepted applications", description="Approved requests.")
- Action.objects.create(team=self.team, name="Deleted action", deleted=True)
+ action = create_action(team=self.team, name="Accepted applications", description="Approved requests.")
+ create_action(team=self.team, name="Deleted action", deleted=True)
EventProperty.objects.create(team=self.team, event="booking_confirmed", property="price")
EventProperty.objects.create(team=self.team, event="booking_confirmed", property="private_amount")
PropertyDefinition.objects.create(team=self.team, name="price", is_numerical=True)
@@ -509,7 +509,7 @@ class TestConversionRecommendations(APIBaseTest):
requests = client.messages.create.call_args_list
catalog = json.loads(requests[0].kwargs["messages"][0]["content"])["catalog"]
refs = {entry["source_ref"] for entry in catalog}
- self.assertIn(f"action:{action.pk}", refs)
+ self.assertIn(f"action:{action.id}", refs)
self.assertIn("event:activity_date_unknown", refs)
self.assertFalse({"event:hidden_event", "event:$pageview", "event:old_event"} & refs)
self.assertEqual(
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 0e25d3af0418..cbbc3ce54fd3 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -541,7 +541,7 @@ product_analytics.Insight posthog.models.file_system.unfiled_file_saver in-colle
product_analytics.Insight posthog.models.product_intent.product_intent instance-many(filter) 2
product_analytics.Insight posthog.models.resource_transfer.visitors.insight other(Return) 1
product_analytics.Insight posthog.models.sharing_configuration passed-as-class(cast) 1
-product_analytics.Insight products.actions.backend.api.action instance-many(extra) 1
+product_analytics.Insight products.actions.backend.presentation.views.action instance-many(extra) 1
product_analytics.Insight products.alerts.backend.max_tools instance-many(filter) 1
product_analytics.Insight products.alerts.backend.max_tools passed-as-class(cast) 1
product_analytics.Insight products.alerts.backend.max_tools write(create) 1
@@ -614,7 +614,7 @@ product_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_alert_su
product_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_metrics_alerts drives(TrendsQuery) 1
product_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_trends_absolute_alerts drives(TrendsQuery) 2
product_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_trends_relative_alerts drives(TrendsQuery) 1
-product_analytics:backend/hogql_queries/ products.actions.backend.api.test.test_action drives(TrendsQuery) 9
+product_analytics:backend/hogql_queries/ products.actions.backend.tests.api.test_action drives(TrendsQuery) 9
product_analytics:backend/hogql_queries/ products.alerts.backend.tests.api.test_alert drives(TrendsQuery) 1
product_analytics:backend/hogql_queries/ products.analytics_platform.backend.lazy_computation.tests.test_lazy_computation_executor drives(TrendsQueryRunner) 2
product_analytics:backend/hogql_queries/ products.cohorts.backend.models.test.test_util drives(TrendsQuery) 1
@@ -981,7 +981,7 @@ web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_alert_subscr
web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_metrics_alerts drives(TrendsQuery) 1
web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_trends_absolute_alerts drives(TrendsQuery) 2
web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_trends_relative_alerts drives(TrendsQuery) 1
-web_analytics:backend/hogql_queries/ products.actions.backend.api.test.test_action drives(TrendsQuery) 9
+web_analytics:backend/hogql_queries/ products.actions.backend.tests.api.test_action drives(TrendsQuery) 9
web_analytics:backend/hogql_queries/ products.alerts.backend.tests.api.test_alert drives(TrendsQuery) 1
web_analytics:backend/hogql_queries/ products.cohorts.backend.models.test.test_util drives(TrendsQuery) 1
web_analytics:backend/hogql_queries/ products.dashboards.backend.api.test.test_dashboard_templates drives(TrendsQuery) 2
diff --git a/products/product_analytics/backend/hogql_queries/funnels/base.py b/products/product_analytics/backend/hogql_queries/funnels/base.py
index 45a8e488cb64..6798e100b3c4 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/base.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/base.py
@@ -28,7 +28,7 @@ from posthog.hogql_queries.utils.sampling import correct_result_for_sampling
from posthog.models.property.property import PropertyName
from posthog.types import FunnelEntityNode
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action, get_action_names
from products.cohorts.backend.models.cohort import Cohort
from products.product_analytics.backend.hogql_queries.funnels.funnel_event_query import FunnelEventQuery
from products.product_analytics.backend.hogql_queries.funnels.funnel_query_context import FunnelQueryContext
@@ -200,8 +200,8 @@ class FunnelBase(ABC):
action_ids = [int(node.id) for node in step.nodes if isinstance(node, ActionsNode)]
actions_by_id = {}
if action_ids:
- actions = Action.objects.filter(pk__in=action_ids, team__project_id=self.context.team.project_id)
- actions_by_id = {action.pk: action.name or "Unnamed action" for action in actions}
+ action_names = get_action_names(project_id=self.context.team.project_id, action_ids=action_ids)
+ actions_by_id = {action_id: name or "Unnamed action" for action_id, name in action_names.items()}
events = []
for node in step.nodes:
@@ -211,7 +211,7 @@ class FunnelBase(ABC):
events.append(actions_by_id.get(int(node.id), "Unnamed action"))
name = ", ".join(events)
elif isinstance(step, ActionsNode):
- action = Action.objects.get(pk=step.id, team__project_id=self.context.team.project_id)
+ action = get_action(action_id=int(step.id), project_id=self.context.team.project_id)
name = action.name
else:
raise TypeError(f"Unsupported step type {type(step)}")
diff --git a/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py b/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py
index ee9777b09362..f9e1d7a9f96a 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py
@@ -37,7 +37,8 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.property.property import PropertyName
from posthog.types import FunnelEntityNode, FunnelExclusionEntityNode
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
from products.product_analytics.backend.hogql_queries.funnels.funnel_aggregation_operations import (
FirstTimeForUserAggregationQuery,
)
@@ -360,8 +361,8 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):
if isinstance(step_entity, ActionsNode) or isinstance(step_entity, FunnelExclusionActionsNode):
# action
try:
- action = Action.objects.get(pk=int(step_entity.id), team__project_id=self.context.team.project_id)
- except Action.DoesNotExist:
+ action = get_action(action_id=int(step_entity.id), project_id=self.context.team.project_id)
+ except ActionNotFound:
raise ValidationError(f"Action ID {step_entity.id} does not exist!")
event_expr = action_to_expr(action)
elif isinstance(step_entity, FunnelsDataWarehouseNode):
@@ -685,9 +686,9 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):
events.add(node.event)
elif isinstance(node, ActionsNode) or isinstance(node, FunnelExclusionActionsNode):
try:
- action = Action.objects.get(pk=int(node.id), team__project_id=self.context.team.project_id)
+ action = get_action(action_id=int(node.id), project_id=self.context.team.project_id)
events.update(action.get_step_events())
- except Action.DoesNotExist:
+ except ActionNotFound:
raise ValidationError(f"Action ID {node.id} does not exist!")
elif isinstance(node, FunnelsDataWarehouseNode):
continue # Data warehouse nodes aren't based on events
@@ -697,9 +698,9 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):
events.add(child.event)
elif isinstance(child, ActionsNode):
try:
- action = Action.objects.get(pk=int(child.id), team__project_id=self.context.team.project_id)
+ action = get_action(action_id=int(child.id), project_id=self.context.team.project_id)
events.update(action.get_step_events())
- except Action.DoesNotExist:
+ except ActionNotFound:
raise ValidationError(f"Action ID {child.id} does not exist!")
else:
continue
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py
index 81c704ba64a1..89e7d0f30420 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py
@@ -63,7 +63,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.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.product_analytics.backend.hogql_queries.funnels.funnels_query_runner import FunnelsQueryRunner
@@ -172,7 +172,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
)
def _basic_funnel(self, query: FunnelsQuery | None = None, properties=None):
- action_credit_card = Action.objects.create(
+ action_credit_card = create_action(
team=self.team,
name="paid",
steps_json=[
@@ -183,7 +183,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
}
],
)
- action_play_movie = Action.objects.create(
+ action_play_movie = create_action(
team=self.team,
name="watched movie",
steps_json=[
@@ -202,8 +202,8 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
event="user signed up",
name="user signed up",
),
- ActionsNode(id=action_credit_card.pk),
- ActionsNode(id=action_play_movie.pk),
+ ActionsNode(id=action_credit_card.id),
+ ActionsNode(id=action_play_movie.id),
],
)
@@ -345,7 +345,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result[2]["count"], 1)
def test_funnel_with_messed_up_order(self):
- action_play_movie = Action.objects.create(
+ action_play_movie = create_action(
team=self.team,
name="watched movie",
steps_json=[
@@ -365,7 +365,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
name="user signed up",
),
ActionsNode(
- id=action_play_movie.pk,
+ id=action_play_movie.id,
),
],
)
@@ -449,7 +449,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
# TODO: obsolete test as new entities aren't part of the query schema?
def test_funnel_with_new_entities_that_mess_up_order(self):
- action_play_movie = Action.objects.create(
+ action_play_movie = create_action(
team=self.team,
name="watched movie",
steps_json=[
@@ -469,7 +469,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
name="user signed up",
),
ActionsNode(
- id=action_play_movie.pk,
+ id=action_play_movie.id,
),
],
)
@@ -540,7 +540,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(["$browser"])
def test_funnel_prop_filters_per_entity(self):
- action_credit_card = Action.objects.create(
+ action_credit_card = create_action(
team_id=self.team.pk,
name="paid",
steps_json=[
@@ -551,7 +551,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
}
],
)
- action_play_movie = Action.objects.create(
+ action_play_movie = create_action(
team_id=self.team.pk,
name="watched movie",
steps_json=[
@@ -580,7 +580,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
],
),
ActionsNode(
- id=action_credit_card.pk,
+ id=action_credit_card.id,
properties=[
{
"key": "$browser",
@@ -589,7 +589,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
],
),
ActionsNode(
- id=action_play_movie.pk,
+ id=action_play_movie.id,
properties=[
{
"key": "$browser",
@@ -630,7 +630,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
@also_test_with_materialized_columns(person_properties=["email"])
def test_funnel_person_prop(self):
- action_credit_card = Action.objects.create(
+ action_credit_card = create_action(
team_id=self.team.pk,
name="paid",
steps_json=[
@@ -641,7 +641,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
}
],
)
- action_play_movie = Action.objects.create(
+ action_play_movie = create_action(
team_id=self.team.pk,
name="watched movie",
steps_json=[
@@ -667,10 +667,10 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
],
),
ActionsNode(
- id=action_credit_card.pk,
+ id=action_credit_card.id,
),
ActionsNode(
- id=action_play_movie.pk,
+ id=action_play_movie.id,
),
],
)
@@ -705,7 +705,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
team=self.team,
)
- action1 = Action.objects.create(
+ action1 = create_action(
team_id=self.team.pk,
name="event2",
steps_json=[
@@ -715,7 +715,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
}
],
)
- action2 = Action.objects.create(
+ action2 = create_action(
team_id=self.team.pk,
name="event2",
steps_json=[
@@ -733,10 +733,10 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
name="event1",
),
ActionsNode(
- id=action1.pk,
+ id=action1.id,
),
ActionsNode(
- id=action2.pk,
+ id=action2.id,
),
],
)
@@ -831,7 +831,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
_create_event(distinct_id="person2", event="event1", team=self.team)
_create_event(distinct_id="person3", event="event1", team=self.team)
- action = Action.objects.create(
+ action = create_action(
team_id=self.team.pk,
name="event1",
steps_json=[
@@ -852,10 +852,10 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
query = FunnelsQuery(
series=[
ActionsNode(
- id=action.pk,
+ id=action.id,
),
ActionsNode(
- id=action.pk,
+ id=action.id,
),
],
)
@@ -3700,7 +3700,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[0]["count"], 0)
def test_funnel_with_sampling(self):
- action_play_movie = Action.objects.create(
+ action_play_movie = create_action(
team=self.team,
name="watched movie",
steps_json=[
@@ -3721,7 +3721,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
name="user signed up",
),
ActionsNode(
- id=action_play_movie.pk,
+ id=action_play_movie.id,
),
],
)
@@ -3937,7 +3937,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
self._signup_event(distinct_id="user")
self._add_to_cart_event(distinct_id="user", properties={"is_saved": True})
- action_checkout_all = Action.objects.create(
+ action_checkout_all = create_action(
team=self.team,
name="user signed up",
steps_json=[
@@ -3953,7 +3953,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
name="user signed up",
),
ActionsNode(
- id=action_checkout_all.pk,
+ id=action_checkout_all.id,
),
],
)
@@ -4013,7 +4013,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
properties={"email": "[email protected]"},
)
- Action.objects.create(team=self.team, name="action1", steps_json=[{"event": "$pageview"}])
+ create_action(team=self.team, name="action1", steps_json=[{"event": "$pageview"}])
cohort = Cohort.objects.create(
team=self.team,
@@ -4554,7 +4554,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[1]["count"], 0)
def test_first_time_for_user_funnel_with_actions(self):
- action_credit_card = Action.objects.create(
+ action_credit_card = create_action(
team=self.team,
name="paid",
steps_json=[
@@ -4565,7 +4565,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
}
],
)
- action_play_movie = Action.objects.create(
+ action_play_movie = create_action(
team=self.team,
name="watched movie",
steps_json=[
@@ -4607,8 +4607,8 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
query = FunnelsQuery(
series=[
EventsNode(event="user signed up"),
- ActionsNode(id=action_credit_card.pk),
- ActionsNode(id=action_play_movie.pk, math=BaseMathType.FIRST_TIME_FOR_USER),
+ ActionsNode(id=action_credit_card.id),
+ ActionsNode(id=action_play_movie.id, math=BaseMathType.FIRST_TIME_FOR_USER),
],
dateRange=DateRange(
date_from="-14d",
@@ -5832,7 +5832,7 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result[1]["count"], 1)
def test_group_node_with_action_child(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Page Action",
steps_json=[{"event": "$pageview"}, {"event": "$pageleave"}],
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py
index b57e8cfa101f..312b9b8db02e 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_event_query.py
@@ -24,7 +24,7 @@ from posthog.schema import (
from posthog.hogql import ast
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.product_analytics.backend.hogql_queries.funnels.funnel_event_query import FunnelEventQuery
from products.product_analytics.backend.hogql_queries.funnels.funnel_query_context import FunnelQueryContext
from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
@@ -487,7 +487,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
@time_machine.travel("2025-11-12", tick=False)
def test_group_node_between_event_and_action(self):
- checkout_action = Action.objects.create(
+ checkout_action = create_action(
team=self.team,
name="Checkout Action",
steps_json=[{"event": "checkout"}, {"event": "purchase"}],
@@ -552,7 +552,7 @@ class TestFunnelEventQuery(ClickhouseTestMixin, APIBaseTest):
@time_machine.travel("2025-11-12", tick=False)
def test_group_node_event_or_action(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Onboarding",
steps_json=[{"event": "sign up"}, {"event": "onboarding completed"}],
diff --git a/products/product_analytics/backend/hogql_queries/lifecycle/lifecycle_query_runner.py b/products/product_analytics/backend/hogql_queries/lifecycle/lifecycle_query_runner.py
index f9993712f618..6e250aede434 100644
--- a/products/product_analytics/backend/hogql_queries/lifecycle/lifecycle_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/lifecycle_query_runner.py
@@ -35,7 +35,8 @@ 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 products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
from products.product_analytics.backend.hogql_queries.lifecycle.lifecycle_validation_rules import (
RequireLifecycleDataWarehouseSeriesForCustomAggregationTarget,
)
@@ -238,7 +239,7 @@ class LifecycleQueryRunner(AnalyticsQueryRunner[LifecycleQueryResponse]):
label = "{} - {}".format("", status)
if isinstance(series, ActionsNode):
- action = Action.objects.get(pk=int(series.id), team__project_id=self.team.project_id)
+ action = get_action(action_id=int(series.id), project_id=self.team.project_id)
label = "{} - {}".format(action.name, status)
elif isinstance(series, EventsNode):
event = series.event
@@ -361,8 +362,8 @@ class LifecycleQueryRunner(AnalyticsQueryRunner[LifecycleQueryResponse]):
for series in self.query.series or []:
if isinstance(series, ActionsNode):
try:
- action = Action.objects.get(pk=int(series.id), team__project_id=self.team.project_id)
- except Action.DoesNotExist:
+ action = get_action(action_id=int(series.id), project_id=self.team.project_id)
+ except ActionNotFound:
raise ValidationError(f"Action ID {series.id} does not exist!")
event_filters.append(action_to_expr(action))
elif isinstance(series, EventsNode):
diff --git a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py
index 9af417be6a60..473e7e75224f 100644
--- a/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/lifecycle/test/test_lifecycle_query_runner.py
@@ -40,7 +40,7 @@ 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
+from products.actions.backend.facade import testing as action_fixtures
from products.cohorts.backend.models.cohort import Cohort
from products.product_analytics.backend.hogql_queries.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
@@ -49,7 +49,7 @@ def create_action(**kwargs):
team = kwargs.pop("team")
name = kwargs.pop("name")
event_name = kwargs.pop("event_name")
- action = Action.objects.create(team=team, name=name, steps_json=[{"event": event_name}])
+ action = action_fixtures.create_action(team=team, name=name, steps_json=[{"event": event_name}])
return action
@@ -1695,7 +1695,7 @@ class TestLifecycleQueryRunner(ClickhouseTestMixin, APIBaseTest):
query=LifecycleQuery(
dateRange=DateRange(date_from="2020-01-12T00:00:00Z", date_to="2020-01-19T00:00:00Z"),
interval=IntervalType.DAY,
- series=[ActionsNode(id=pageview_action.pk)],
+ series=[ActionsNode(id=pageview_action.id)],
),
).calculate()
@@ -1708,7 +1708,7 @@ class TestLifecycleQueryRunner(ClickhouseTestMixin, APIBaseTest):
{"status": "returning", "data": [1, 1, 0, 0, 0, 0, 0, 0]},
],
)
- assert response.action_names == {str(pageview_action.pk): "$pageview"}
+ assert response.action_names == {str(pageview_action.id): "$pageview"}
def test_lifecycle_trend_all_time(self):
self._create_events(
diff --git a/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py b/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
index c12ff5d7770f..48c594b9c276 100644
--- a/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/retention/retention_query_runner.py
@@ -49,7 +49,7 @@ from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
from products.product_analytics.backend.hogql_queries.retention.retention_base_query_fixed import (
RetentionFixedIntervalBaseQueryBuilder,
)
@@ -409,7 +409,7 @@ class RetentionQueryRunner(AnalyticsQueryRunner[RetentionQueryResponse]):
def get_events_for_entity(self, entity: RetentionEntity) -> list[str | None]:
if entity.type == EntityType.ACTIONS and entity.id:
- action = Action.objects.get(pk=int(entity.id), team__project_id=self.team.project_id)
+ action = get_action(action_id=int(entity.id), project_id=self.team.project_id)
return action.get_step_events()
return [entity.id] if isinstance(entity.id, str) else [None]
diff --git a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
index 2d2c23fb6ec9..ce782f8a4c87 100644
--- a/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/retention/test/test_retention_query_runner.py
@@ -42,7 +42,7 @@ from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from posthog.test.persons import create_person, update_person
from posthog.test.test_utils import create_group_type_mapping_without_created_at
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.product_analytics.backend.hogql_queries.retention.retention_base_query_fixed import (
@@ -1133,7 +1133,7 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
),
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[
{
@@ -1614,7 +1614,7 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
"retentionFilter": {
"totalIntervals": 7,
"targetEntity": {
- "id": action.pk,
+ "id": action.id,
"name": action.name,
"type": TREND_FILTER_TYPE_ACTIONS,
},
@@ -2113,7 +2113,7 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result[0]["values"][1]["count"], 1)
def test_retention_with_properties_on_action_target_entity(self):
- action = Action.objects.create(team=self.team, name="pageview_action", steps_json=[{"event": "$pageview"}])
+ action = create_action(team=self.team, name="pageview_action", steps_json=[{"event": "$pageview"}])
_create_person(team_id=self.team.pk, distinct_ids=["person1"])
_create_person(team_id=self.team.pk, distinct_ids=["person2"])
@@ -2135,7 +2135,7 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
"period": "Day",
"totalIntervals": 7,
"targetEntity": {
- "id": action.pk,
+ "id": action.id,
"type": TREND_FILTER_TYPE_ACTIONS,
"properties": [
{
@@ -2154,7 +2154,7 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(result[0]["values"][0]["count"], 1)
def test_retention_with_properties_on_action_returning_entity(self):
- action = Action.objects.create(team=self.team, name="pageview_action", steps_json=[{"event": "$pageview"}])
+ action = create_action(team=self.team, name="pageview_action", steps_json=[{"event": "$pageview"}])
_create_person(team_id=self.team.pk, distinct_ids=["person1"])
_create_person(team_id=self.team.pk, distinct_ids=["person2"])
@@ -2177,7 +2177,7 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
"totalIntervals": 7,
"targetEntity": {"id": "$pageview", "type": TREND_FILTER_TYPE_EVENTS},
"returningEntity": {
- "id": action.pk,
+ "id": action.id,
"type": TREND_FILTER_TYPE_ACTIONS,
"properties": [
{
@@ -2430,7 +2430,7 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
@snapshot_clickhouse_queries
def test_retention_with_user_properties_via_action(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
steps_json=[
{
@@ -2473,7 +2473,7 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
"dateRange": {"date_to": _date(6, hour=0)},
"retentionFilter": {
"totalIntervals": 7,
- "targetEntity": {"id": action.pk, "name": action.name, "type": TREND_FILTER_TYPE_ACTIONS},
+ "targetEntity": {"id": action.id, "name": action.name, "type": TREND_FILTER_TYPE_ACTIONS},
"returningEntity": {"id": "$pageview", "name": "$pageview", "type": "events"},
},
}
@@ -2526,8 +2526,8 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
"retentionFilter": {
"period": "Day",
"totalIntervals": 7,
- "targetEntity": {"id": action.pk, "name": action.name, "type": TREND_FILTER_TYPE_ACTIONS},
- "returningEntity": {"id": action.pk, "name": action.name, "type": TREND_FILTER_TYPE_ACTIONS},
+ "targetEntity": {"id": action.id, "name": action.name, "type": TREND_FILTER_TYPE_ACTIONS},
+ "returningEntity": {"id": action.id, "name": action.name, "type": TREND_FILTER_TYPE_ACTIONS},
},
}
)
@@ -5228,7 +5228,7 @@ class TestRetention(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="act_a on dash",
steps_json=[{"event": "act_a", "url": "/dash", "url_matching": "contains"}],
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 8590f766f535..8764839b69f5 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
@@ -41,7 +41,8 @@ from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
from products.cohorts.backend.models.util import get_count_operator, get_count_operator_ast
@@ -335,7 +336,7 @@ class StickinessQueryRunner(AnalyticsQueryRunner[StickinessQueryResponse]):
try:
series_label = self.series_event(series_with_extra.series)
- except Action.DoesNotExist:
+ except ActionNotFound:
# Dont append the series if the action doesnt exist
continue
@@ -425,9 +426,9 @@ class StickinessQueryRunner(AnalyticsQueryRunner[StickinessQueryResponse]):
)
elif isinstance(series, ActionsNode):
try:
- action = Action.objects.get(pk=int(series.id), team__project_id=self.team.project_id)
+ action = get_action(action_id=int(series.id), project_id=self.team.project_id)
filters.append(action_to_expr(action))
- except Action.DoesNotExist:
+ except ActionNotFound:
# If an action doesn't exist, we want to return no events
filters.append(parse_expr("1 = 2"))
@@ -486,7 +487,7 @@ class StickinessQueryRunner(AnalyticsQueryRunner[StickinessQueryResponse]):
if isinstance(series, ActionsNode):
# TODO: Can we load the Action in more efficiently?
- action = Action.objects.get(pk=int(series.id), team__project_id=self.team.project_id)
+ action = get_action(action_id=int(series.id), project_id=self.team.project_id)
return action.name
def setup_series(self) -> list[SeriesWithExtras]:
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 a9d1d6b7206a..77a468c54c0f 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
@@ -59,7 +59,7 @@ 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.actions.backend.facade.testing import create_action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.product_analytics.backend.hogql_queries.stickiness.stickiness_query_runner import StickinessQueryRunner
from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
@@ -731,7 +731,7 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_actions(self):
self._create_test_events()
- action = Action.objects.create(
+ action = create_action(
name="My Action",
team=self.team,
steps_json=[
@@ -742,7 +742,7 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):
],
)
- series: list[EventsNode | ActionsNode] = [ActionsNode(id=action.pk)]
+ series: list[EventsNode | ActionsNode] = [ActionsNode(id=action.id)]
response = self._run_query(series=series)
@@ -1600,7 +1600,7 @@ class TestStickinessDashboardFilters(BaseTest):
class TestStickinessCacheHit(BaseTest):
def test_a_response_cached_by_an_older_runner_reads_like_a_fresh_one(self) -> None:
- action = Action.objects.create(team=self.team, name="Signed up")
+ action = create_action(team=self.team, name="Signed up")
query = StickinessQuery(series=[EventsNode(event="$pageview"), ActionsNode(id=action.id)])
cached_rows = [
{"label": "$pageview", "data": [3], "order": 0},
diff --git a/products/product_analytics/backend/hogql_queries/trends/calendar_heatmap_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/calendar_heatmap_query_runner.py
index 6d347b85fa27..51a721203364 100644
--- a/products/product_analytics/backend/hogql_queries/trends/calendar_heatmap_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/calendar_heatmap_query_runner.py
@@ -41,7 +41,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.product_analytics.backend.hogql_queries.trends.series_with_extras import SeriesWithExtras
from products.web_analytics.backend.hogql_queries.first_pageview_attribution import (
@@ -375,7 +375,7 @@ class CalendarHeatmapQueryRunner(AnalyticsQueryRunner[CalendarHeatmapResponse]):
@cached_property
def conversion_goal_expr(self) -> Optional[ast.Expr]:
if self.query.series[0].kind == "ActionsNode":
- action = Action.objects.get(pk=self.query.series[0].id, team__project_id=self.team.project_id)
+ action = get_action(action_id=int(self.query.series[0].id), project_id=self.team.project_id)
return action_to_expr(action)
elif isinstance(self.query.conversionGoal, CustomEventConversionGoal):
return ast.CompareOperation(
@@ -387,7 +387,7 @@ class CalendarHeatmapQueryRunner(AnalyticsQueryRunner[CalendarHeatmapResponse]):
# Support for web analytics
if isinstance(self.query.conversionGoal, ActionConversionGoal):
- action = Action.objects.get(pk=self.query.conversionGoal.actionId, team__project_id=self.team.project_id)
+ action = get_action(action_id=int(self.query.conversionGoal.actionId), project_id=self.team.project_id)
return action_to_expr(action)
else:
return None
@@ -423,7 +423,7 @@ class CalendarHeatmapQueryRunner(AnalyticsQueryRunner[CalendarHeatmapResponse]):
return series.event
if isinstance(series, ActionsNode):
# TODO: Can we load the Action in more efficiently?
- action = Action.objects.get(pk=int(series.id), team__project_id=self.team.project_id)
+ action = get_action(action_id=int(series.id), project_id=self.team.project_id)
return action.name
if isinstance(series, DataWarehouseNode):
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_calendar_heatmap_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/test/test_calendar_heatmap_query_runner.py
index ececf95f7df1..63a243ca8f26 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_calendar_heatmap_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_calendar_heatmap_query_runner.py
@@ -16,7 +16,7 @@ from posthog.schema import (
from posthog.models.utils import uuid7
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.product_analytics.backend.hogql_queries.trends.calendar_heatmap_query_runner import (
CalendarHeatmapQueryRunner,
)
@@ -280,7 +280,7 @@ class TestCalendarHeatmapQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert results_dict.get((6, 10)) == 1, f"Expected 1 custom event, got {results_dict.get((6, 10))}"
def test_action_conversion_goal(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Did Custom Event",
steps_json=[
@@ -692,7 +692,7 @@ class TestCalendarHeatmapQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_complex_actions_with_multiple_steps(self):
"""Test calendar heatmap with complex actions containing multiple steps"""
# Create a complex action with multiple events
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Complex User Journey",
steps_json=[
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py
index d0dfed9422a4..532e2fd74600 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends.py
@@ -68,7 +68,8 @@ from posthog.test.persons import create_person
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.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.product_analytics.backend.hogql_queries.trends.test.test_trends_persons import get_actors
@@ -3470,8 +3471,12 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
def test_action_filtering_for_action_in_different_env_of_project(self):
sign_up_action, person = self._create_events()
other_team_in_project = Team.objects.create(organization=self.organization, project=self.project)
- sign_up_action.team = other_team_in_project
- sign_up_action.save()
+ # The same action, owned by another environment of the project.
+ sign_up_action = create_action(
+ team=other_team_in_project,
+ name=sign_up_action.name,
+ steps_json=[dataclasses.asdict(step) for step in sign_up_action.steps],
+ )
action_response = self._run_query(
TrendsQuery(
@@ -3627,7 +3632,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
self._create_event(team=self.team, event="$pageview", distinct_id="d3")
self._create_event(team=self.team, event="$pageview", distinct_id="d4")
- event_filtering_action = Action.objects.create(
+ event_filtering_action = create_action(
team=self.team,
name="$pageview from non-internal",
steps_json=[
@@ -4190,7 +4195,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
),
series=[
ActionsNode(
- id=action.pk,
+ id=action.id,
),
],
),
@@ -4488,7 +4493,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
TrendsQuery(
breakdownFilter=breakdown_filter,
dateRange=DateRange(date_from="-14d"),
- series=[ActionsNode(id=action.pk)],
+ series=[ActionsNode(id=action.id)],
),
self.team,
)
@@ -5413,7 +5418,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
PropertyGroupFilterValue(type=FilterLogicalOperator.AND_, values=[person_filter]),
],
),
- series=[ActionsNode(id=action.pk)],
+ series=[ActionsNode(id=action.id)],
)
def event_query(breakdown_filter: BreakdownFilter) -> TrendsQuery:
@@ -5723,7 +5728,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
),
series=[
ActionsNode(
- id=action.pk,
+ id=action.id,
),
],
),
@@ -6380,7 +6385,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
distinct_ids=["blabla", "anonymous_id"],
properties={"$some_prop": "some_val"},
)
- sign_up_action = Action.objects.create(
+ sign_up_action = create_action(
team=self.team,
name="sign up",
steps_json=[
@@ -6492,11 +6497,10 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
groups=[{"properties": [{"key": "$some_prop", "value": "some_val", "type": "person"}]}],
)
- step = sign_up_action.steps[0]
- step.properties = [{"key": "id", "value": cohort.pk, "type": "cohort"}]
-
- sign_up_action.steps = [dataclasses.asdict(step)]
- sign_up_action.save()
+ step = dataclasses.replace(
+ sign_up_action.steps[0], properties=[{"key": "id", "value": cohort.pk, "type": "cohort"}]
+ )
+ sign_up_action = update_action(sign_up_action, steps_json=[dataclasses.asdict(step)])
cohort.calculate_people_ch(pending_version=0)
@@ -7761,7 +7765,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
properties={"key": "val", "$current_url": "/another/page"},
)
- action = Action.objects.create(
+ action = create_action(
name="sign up",
team=self.team,
steps_json=[
@@ -7780,7 +7784,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):
),
series=[
ActionsNode(
- id=action.pk,
+ id=action.id,
),
],
),
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_persons.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_persons.py
index 80f494b618ce..445c5944a3a9 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_persons.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_persons.py
@@ -41,7 +41,7 @@ from posthog.models import Team
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.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
@@ -1698,7 +1698,7 @@ class TestTrendsPersons(ClickhouseTestMixin, APIBaseTest):
def test_trends_math_first_time_for_user_actions(self):
self._create_events()
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="viewed from chrome or safari",
steps_json=[
@@ -1729,7 +1729,7 @@ class TestTrendsPersons(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(get_distinct_id(result[0]), "person3")
self.assertEqual(get_event_count(result[0]), 1)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="viewed from chrome and left",
steps_json=[
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
index 282bf05aa13d..411b3e59b3ce 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
@@ -83,7 +83,7 @@ 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.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
@@ -99,7 +99,7 @@ def _flag_call_event_series(team: Team, flag_keys: list[str]) -> EventsNode:
def _flag_call_action_series(team: Team, flag_keys: list[str]) -> ActionsNode:
- action = Action.objects.create(
+ action = create_action(
team=team,
name="called a flag",
steps_json=[
@@ -6598,7 +6598,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self._create_test_events()
flush_persons_and_events()
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="viewed from chrome and left",
steps_json=[
@@ -6625,7 +6625,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.results[0]["count"] == 1
assert response.results[0]["data"] == [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="viewed from chrome or firefox",
steps_json=[
@@ -7997,7 +7997,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
flush_persons_and_events()
# Create an action for pageview
- page_action = Action.objects.create(
+ page_action = create_action(
team=self.team,
name="Pageview Action",
steps_json=[
@@ -8121,7 +8121,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
flush_persons_and_events()
# Page Action combines both pageview and pageleave events
- page_action = Action.objects.create(
+ page_action = create_action(
team=self.team,
name="Page Action",
steps_json=[
@@ -8130,7 +8130,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
],
)
- pageview_action = Action.objects.create(
+ pageview_action = create_action(
team=self.team,
name="Pageview Action",
steps_json=[
diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_actors_query_builder.py b/products/product_analytics/backend/hogql_queries/trends/trends_actors_query_builder.py
index 510236b349fc..f4c503a071ac 100644
--- a/products/product_analytics/backend/hogql_queries/trends/trends_actors_query_builder.py
+++ b/products/product_analytics/backend/hogql_queries/trends/trends_actors_query_builder.py
@@ -32,7 +32,8 @@ 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 Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
from products.product_analytics.backend.hogql_queries.trends.aggregation_operations import (
AggregationOperations,
FirstTimeForUserEventsQueryAlternator,
@@ -390,9 +391,9 @@ class TrendsActorsQueryBuilder:
if isinstance(self.entity, ActionsNode):
# Actions
try:
- action = Action.objects.get(pk=int(self.entity.id), team__project_id=self.team.project_id)
+ action = get_action(action_id=int(self.entity.id), project_id=self.team.project_id)
return action_to_expr(action)
- except Action.DoesNotExist:
+ except ActionNotFound:
# If an action doesn't exist, we want to return no events
return parse_expr("1 = 2")
elif isinstance(self.entity, EventsNode):
diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_query_builder.py b/products/product_analytics/backend/hogql_queries/trends/trends_query_builder.py
index e2ba01af0ac6..49435075feb0 100644
--- a/products/product_analytics/backend/hogql_queries/trends/trends_query_builder.py
+++ b/products/product_analytics/backend/hogql_queries/trends/trends_query_builder.py
@@ -24,7 +24,8 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.team.team import Team
from posthog.ph_client import feature_enabled_or_false
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
from products.product_analytics.backend.hogql_queries.trends.aggregation_operations import AggregationOperations
from products.product_analytics.backend.hogql_queries.trends.breakdown import Breakdown
from products.product_analytics.backend.hogql_queries.trends.display import TrendsDisplay
@@ -903,9 +904,9 @@ class TrendsQueryBuilder(DataWarehouseInsightQueryMixin):
def _get_action_expr(self, series: ActionsNode) -> ast.Expr | None:
try:
- action = Action.objects.get(pk=int(series.id), team__project_id=self.team.project_id)
+ action = get_action(action_id=int(series.id), project_id=self.team.project_id)
return action_to_expr(action)
- except Action.DoesNotExist:
+ except ActionNotFound:
# If an action doesn't exist, we want to return no events
return parse_expr("1 = 2")
diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
index eb822f14bfe1..3234faeaea4b 100644
--- a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
@@ -82,7 +82,8 @@ from posthog.models.user import User
from posthog.ph_client import feature_enabled_or_false
from posthog.utils import multisort
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade import api as actions_facade
+from products.actions.backend.facade.contracts import ActionNotFound
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.product_analytics.backend.hogql_queries.trends.display import TrendsDisplay
@@ -648,7 +649,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
for val in response.results:
try:
series_label = self.series_event(series.series)
- except Action.DoesNotExist:
+ except ActionNotFound:
# Dont append the series if the action doesnt exist
continue
@@ -886,7 +887,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
return series.event
if isinstance(series, ActionsNode):
# TODO: Can we load the Action in more efficiently?
- action = Action.objects.get(pk=int(series.id), team__project_id=self.team.project_id)
+ action = actions_facade.get_action(action_id=int(series.id), project_id=self.team.project_id)
return action.name
if isinstance(series, DataWarehouseNode):
@@ -897,8 +898,8 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
action_ids = [int(node.id) for node in series.nodes if isinstance(node, ActionsNode)]
actions_by_id = {}
if action_ids:
- actions = Action.objects.filter(pk__in=action_ids, team__project_id=self.team.project_id)
- actions_by_id = {action.pk: action.name or "Unnamed action" for action in actions}
+ action_names = actions_facade.get_action_names(project_id=self.team.project_id, action_ids=action_ids)
+ actions_by_id = {action_id: name or "Unnamed action" for action_id, name in action_names.items()}
events = []
for node in series.nodes:
@@ -921,7 +922,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
# The series label costs a query for an action series, so it is resolved only when a `name` needs comparing
try:
series_label = self.series_event(series)
- except Action.DoesNotExist:
+ except ActionNotFound:
# build_series_response drops a series whose action is gone, so no row reads this name
return None
return resolve_series_custom_name(series, series_label)
diff --git a/products/product_analytics/backend/hogql_queries/trends/utils.py b/products/product_analytics/backend/hogql_queries/trends/utils.py
index 0cc211405281..c4f7ddbc1b39 100644
--- a/products/product_analytics/backend/hogql_queries/trends/utils.py
+++ b/products/product_analytics/backend/hogql_queries/trends/utils.py
@@ -66,7 +66,8 @@ def is_groups_math(series: Union[EventsNode, ActionsNode, DataWarehouseNode | Gr
def group_node_to_expr(group: GroupNode, team: Team) -> ast.Expr | None:
- from products.actions.backend.models.action import Action
+ from products.actions.backend.facade.api import get_action
+ from products.actions.backend.facade.contracts import ActionNotFound
# AND grouping isn't supported yet. Validate up front so it fails loudly regardless of how
# many nodes resolve, rather than silently dropping the event filter and matching every event.
@@ -88,12 +89,12 @@ def group_node_to_expr(group: GroupNode, team: Team) -> ast.Expr | None:
group_filters.append(node_expr)
elif isinstance(node, ActionsNode):
try:
- action = Action.objects.get(pk=int(node.id), team__project_id=team.project_id)
+ action = get_action(action_id=int(node.id), project_id=team.project_id)
node_expr = action_to_expr(action)
if node.properties is not None and node.properties != []:
node_expr = ast.And(exprs=[node_expr, property_to_expr(node.properties, team)])
group_filters.append(node_expr)
- except Action.DoesNotExist:
+ except ActionNotFound:
pass
elif isinstance(node, DataWarehouseNode):
# TODO: Support DWH nodes in groups
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index 7f9d7542d283..2e40fb523eaf 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -69,7 +69,7 @@ from posthog.test.db_context_capturing import capture_db_queries
from posthog.test.insight_queries import browser_filtered_pageview_query, default_pageview_query, insight_query
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.alerts.backend.models.alert import AlertConfiguration, AlertSubscription, Threshold
from products.dashboards.backend.facade.access import DashboardAccessMethod
from products.dashboards.backend.models.dashboard import Dashboard
@@ -679,7 +679,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
# never execute the body of. A 200 alone doesn't prove this: insight_result's
# broad except Exception swallows calculation crashes into a query_status error
# and still renders 200, so assert the embedded result actually computed.
- action = Action.objects.create(team=self.team, name="Viewed a page", steps_json=[{"event": "$pageview"}])
+ action = create_action(team=self.team, name="Viewed a page", steps_json=[{"event": "$pageview"}])
query = default_pageview_query()
query["source"]["series"] = [{"kind": "ActionsNode", "id": action.id}]
insight_id, _ = self.dashboard_api.create_insight({"name": "insight", "query": query})
@@ -4472,7 +4472,7 @@ class TestInsightExportCacheShortcut(APIBaseTest):
def test_an_entry_cached_without_action_names_takes_them_from_the_query(
self, mock_query_cache: mock.MagicMock
) -> None:
- action = Action.objects.create(team=self.team, name="Completed checkout")
+ action = create_action(team=self.team, name="Completed checkout")
query = default_pageview_query()
query["source"]["series"] = [{"kind": "ActionsNode", "id": action.id}]
insight = Insight.objects.create(team=self.team, query=query)
diff --git a/products/product_analytics/backend/tests/test_chart_events.py b/products/product_analytics/backend/tests/test_chart_events.py
index d6f561594088..3793a8135c93 100644
--- a/products/product_analytics/backend/tests/test_chart_events.py
+++ b/products/product_analytics/backend/tests/test_chart_events.py
@@ -11,7 +11,7 @@ from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.query import execute_hogql_query
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.product_analytics.backend.chart_events import ChartEvents, chart_events
SERIES = {"kind": "EventsNode", "event": "signed up"}
@@ -82,14 +82,14 @@ class TestChartEventsCounts(ClickhouseTestMixin, BaseTest):
)
_create_event(team=self.team, event="other", distinct_id="person", timestamp=NOW - timedelta(days=1))
flush_persons_and_events()
- self.action = Action.objects.create(
+ self.action = create_action(
team=self.team,
name="Signed up or paid for pro",
steps_json=[{"event": "paid", "properties": PAID_PRO["properties"]}, {"event": "signed up"}],
)
def _chart_events(self, query: dict[str, Any]) -> ChartEvents:
- query = json.loads(json.dumps(query).replace('"ACTION_ID"', str(self.action.pk)))
+ query = json.loads(json.dumps(query).replace('"ACTION_ID"', str(self.action.id)))
events = chart_events({**query, "dateRange": LAST_WEEK}, self.team, self.user)
assert events is not None
return events
diff --git a/products/product_analytics/backend/tests/test_insight_series.py b/products/product_analytics/backend/tests/test_insight_series.py
index 2e36caaa0158..b886aae2de79 100644
--- a/products/product_analytics/backend/tests/test_insight_series.py
+++ b/products/product_analytics/backend/tests/test_insight_series.py
@@ -18,7 +18,7 @@ from posthog.models import Team, User
from posthog.week_start_day import WeekStartDay
from products.access_control.backend.facade.testing import create_access_control
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.product_analytics.backend import insight_series
from products.product_analytics.backend.facade.api import get_insight_series, viewable_insight_definitions
from products.product_analytics.backend.facade.contracts import InsightDashboardContext, InsightSeriesNotReady
@@ -468,12 +468,12 @@ class TestGetInsightSeries(ClickhouseTestMixin, BaseTest):
@override_settings(IN_UNIT_TESTING=True)
def test_a_daily_trend_returns_each_series_with_its_averaging_and_display_format(self) -> None:
self._signups((2, "Chrome"), (2, "Chrome"), (9, "Chrome"))
- action = Action.objects.create(team=self.team, name="Signed up action", steps_json=[{"event": "signed up"}])
+ action = create_action(team=self.team, name="Signed up action", steps_json=[{"event": "signed up"}])
insight = self._insight(
series=[
{"kind": "EventsNode", "event": "signed up", "custom_name": "Sign-ups"},
{"kind": "EventsNode", "event": "signed up", "math": "dau", "custom_name": "Daily people"},
- {"kind": "ActionsNode", "id": action.pk},
+ {"kind": "ActionsNode", "id": action.id},
],
trendsFilter={"aggregationAxisFormat": "percentage", "display": "Metric", "decimalPlaces": 1_000_000},
)
diff --git a/products/product_analytics/backend/tests/test_series_custom_name_cache.py b/products/product_analytics/backend/tests/test_series_custom_name_cache.py
index f514bf8112f5..d7590c294db0 100644
--- a/products/product_analytics/backend/tests/test_series_custom_name_cache.py
+++ b/products/product_analytics/backend/tests/test_series_custom_name_cache.py
@@ -27,7 +27,7 @@ from posthog.schema import (
from posthog.hogql_queries.query_runner import ExecutionMode, QueryRunner
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.product_analytics.backend.hogql_queries.lifecycle.lifecycle_query_runner import LifecycleQueryRunner
from products.product_analytics.backend.hogql_queries.stickiness.stickiness_query_runner import StickinessQueryRunner
from products.product_analytics.backend.hogql_queries.trends.trends_query_runner import TrendsQueryRunner
@@ -138,13 +138,13 @@ class TestSeriesCustomNameCache(BaseTest):
assert [row["custom_name"] for row in results] == [expected_custom_name]
def test_cache_hit_resolves_action_series_names_in_one_query(self) -> None:
- signed_up = Action.objects.create(team=self.team, name="Signed up", steps_json=[{"event": "signed up"}])
- paid = Action.objects.create(team=self.team, name="Paid", steps_json=[{"event": "paid"}])
+ signed_up = create_action(team=self.team, name="Signed up", steps_json=[{"event": "signed up"}])
+ paid = create_action(team=self.team, name="Paid", steps_json=[{"event": "paid"}])
query = TrendsQuery(
series=[
- ActionsNode(id=signed_up.pk, name="Signed up"),
- ActionsNode(id=paid.pk, name="Converted"),
- ActionsNode(id=paid.pk, name="Revenue"),
+ ActionsNode(id=signed_up.id, name="Signed up"),
+ ActionsNode(id=paid.id, name="Converted"),
+ ActionsNode(id=paid.id, name="Revenue"),
]
)
cached_rows = [{"order": order, "custom_name": None, "data": [1]} for order in range(3)]
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 8cbf4ecd9fe0..d812078138ee 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -307,11 +307,7 @@ def query_reference_error(
for kind, ids in (("action", refs.actions), ("cohort", refs.cohorts)):
if ids and kind not in kinds:
return f"This recording filter uses {kind}s, which your access doesn't cover."
- missing = unresolved_references(
- query,
- team,
- can_read_action=lambda action: bool(user_access_control.check_access_level_for_object(action, "viewer")),
- )
+ missing = unresolved_references(query, team, access_control=user_access_control)
if missing:
return f"This recording filter uses {', '.join(missing)}, which this project doesn't have."
return None
diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.py
index c4f6f8e72d31..7e615f5158b1 100644
--- a/products/replay_vision/backend/scanner_draft.py
+++ b/products/replay_vision/backend/scanner_draft.py
@@ -36,7 +36,9 @@ from posthog.schema import RecordingsQuery
from posthog.api.search import (
ENTITY_MAP as _SEARCH_ENTITY_MAP,
EntityConfig,
+ FacadeSearch,
search_entities,
+ search_live_actions,
)
from posthog.clickhouse.query_tagging import get_query_tags, query_tags
from posthog.hogql_queries.utils.parallel import run_in_parallel_threads
@@ -173,9 +175,10 @@ _MAX_FILTER_EVENT_PROPERTIES = 2
# who answered it is a real goal.
_LIVE_SEARCH_ENTITY_MAP: dict[str, EntityConfig] = {
**_SEARCH_ENTITY_MAP,
- "action": {**_SEARCH_ENTITY_MAP["action"], "filters": {"deleted": False}},
"cohort": {**_SEARCH_ENTITY_MAP["cohort"], "filters": {"deleted": False}},
}
+# Actions are searched through the actions facade, not the union map, so they are left out the same way here.
+_LIVE_FACADE_SEARCHES: dict[str, FacadeSearch] = {"action": search_live_actions}
# Words common to almost any goal. Matching them returns arbitrary events rather than the ones the
# user means, and crowds out the terms that carry the intent.
_GOAL_STOPWORDS = frozenset(
@@ -1094,6 +1097,7 @@ def _goal_entity_matches(
view=view, # type: ignore[arg-type]
entity_map=_LIVE_SEARCH_ENTITY_MAP,
include_counts=False,
+ facade_searches=_LIVE_FACADE_SEARCHES,
)
for result in results:
extra = result.get("extra_fields") or {}
diff --git a/products/replay_vision/backend/scanner_query.py b/products/replay_vision/backend/scanner_query.py
index efb013d0bde9..fe2d1996bba8 100644
--- a/products/replay_vision/backend/scanner_query.py
+++ b/products/replay_vision/backend/scanner_query.py
@@ -7,9 +7,8 @@ filter, so they share these rules rather than each keeping a copy that can drift
"""
import json
-from collections.abc import Callable
from enum import StrEnum
-from typing import Any
+from typing import TYPE_CHECKING, Any
from pydantic import (
BaseModel,
@@ -28,9 +27,12 @@ from posthog.dataclasses import frozen
from posthog.models.team import Team
from posthog.session_recordings.queries.sub_queries.events_subquery import ReplayFiltersEventsSubQuery
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import existing_action_ids, readable_action_ids
from products.cohorts.backend.models.cohort import Cohort
+if TYPE_CHECKING:
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
# A scanner's schedule owns time, so a saved filter never carries a date range.
DATE_FIELDS = ("date_from", "date_to")
# A query can carry the rows it last returned, which may hold person data, and are never part of a filter.
@@ -104,7 +106,7 @@ def replay_list_only_fields(query: dict[str, Any]) -> list[str]:
def unresolved_references(
- query: dict[str, Any], team: Team, *, can_read_action: Callable[[Action], bool] = lambda action: True
+ query: dict[str, Any], team: Team, *, access_control: "UserAccessControl | None" = None
) -> list[str]:
"""The actions and cohorts `query` names that a scan cannot load, described for the caller.
@@ -112,17 +114,19 @@ def unresolved_references(
excluded, so a filter this accepts always builds. Without the check, the estimate fails the same
way a timeout does, and a broken filter saves into a scanner whose runs keep failing.
- An action `can_read_action` refuses reads as unresolved too, so the result never tells a caller
- that an id they cannot read exists.
+ With `access_control`, an action the user cannot view counts as unresolved too, so the result never
+ tells a caller that an id they cannot read exists.
"""
refs = query_references(query, team)
action_ids = {ref for ref in refs.actions if isinstance(ref, int)}
cohort_ids = {ref for ref in refs.cohorts if isinstance(ref, int)}
- found_actions = {
- action.id
- for action in Action.objects.filter(pk__in=action_ids, team__project_id=team.project_id)
- if can_read_action(action)
- }
+ found_actions = (
+ readable_action_ids(
+ project_id=team.project_id, action_ids=action_ids, access_control=access_control, required_level="viewer"
+ )
+ if access_control is not None
+ else set(existing_action_ids(project_id=team.project_id, action_ids=action_ids))
+ )
found_cohorts = set(
Cohort.objects.filter(pk__in=cohort_ids, team__project_id=team.project_id, deleted=False).values_list(
"id", flat=True
diff --git a/products/replay_vision/backend/tests/test_action_volume.py b/products/replay_vision/backend/tests/test_action_volume.py
index 8b7e4515562b..27e4b2225684 100644
--- a/products/replay_vision/backend/tests/test_action_volume.py
+++ b/products/replay_vision/backend/tests/test_action_volume.py
@@ -6,7 +6,8 @@ from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_
from posthog.models import Team
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action
from products.replay_vision.backend.queries.action_volume import recent_action_sessions
_NOW = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)
@@ -24,7 +25,7 @@ def _event(team, event: str, session_id: str, at: dt.datetime) -> None:
def _action(team, name: str, event: str) -> Action:
- return Action.objects.create(team=team, name=name, steps_json=[{"event": event}])
+ return create_action(team=team, name=name, steps_json=[{"event": event}])
class TestRecentActionSessions(ClickhouseTestMixin):
@@ -59,7 +60,7 @@ class TestRecentActionSessions(ClickhouseTestMixin):
def test_an_action_with_no_steps_is_never_measured(self, team) -> None:
# A stepless action compiles to a condition that matches every event, so measuring it would
# report the team's whole session count and read as the liveliest action in the briefing.
- stepless = Action.objects.create(team=team, name="Never finished", steps_json=[])
+ stepless = create_action(team=team, name="Never finished", steps_json=[])
_event(team, "checkout completed", "s1", _NOW - dt.timedelta(hours=2))
# This path returns before it queries, and `_create_event` only writes its batch when a
# query runs. Without the flush the event stays pending and fails the next test's teardown.
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 24bc5d4b7c36..53cd23cec78e 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -35,7 +35,7 @@ from posthog.redis import get_client
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import Experiment
from products.replay_vision.backend.api.scanners import HighlightFeedQuerySerializer, ReplayScannerSerializer
@@ -4324,7 +4324,7 @@ class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):
{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
]
self.organization.save()
- action = Action.objects.create(team=self.team, name="Restricted", created_by=self.user)
+ action = create_action(team=self.team, name="Restricted", created_by=self.user)
AccessControl.objects.create(team=self.team, resource="action", resource_id=str(action.id), access_level="none")
member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
self.client.force_login(member)
diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.py
index ffa6b835c8bc..164ec1ff7162 100644
--- a/products/replay_vision/backend/tests/test_scanner_draft.py
+++ b/products/replay_vision/backend/tests/test_scanner_draft.py
@@ -18,7 +18,7 @@ from posthog.models import EventDefinition, PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.rate_limit import AIBurstRateThrottle
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -1010,7 +1010,7 @@ class TestGoalEntityMatches(_VisionAPITestCase):
def test_an_action_named_in_the_goal_comes_back_with_its_id(self):
# An action is the team's own curated definition of a behavior, so a goal naming one is the
# sharpest filter available and must come back with the id the query needs.
- action = Action.objects.create(team=self.team, name="Completed checkout")
+ action = create_action(team=self.team, name="Completed checkout")
matches = _goal_entity_matches(
self.team, "sessions where someone completed checkout", _access_control(allow=True)
@@ -1021,7 +1021,7 @@ class TestGoalEntityMatches(_VisionAPITestCase):
def test_an_entity_the_caller_cannot_read_is_never_named_back(self):
# Surveys and actions are access-controlled, so naming one back would leak its existence.
self._survey("Pricing feedback")
- Action.objects.create(team=self.team, name="Pricing feedback click")
+ create_action(team=self.team, name="Pricing feedback click")
matches = _goal_entity_matches(self.team, "the pricing feedback survey", _access_control(allow=False))
assert (matches.surveys, matches.actions, matches.cohorts) == ([], [], [])
@@ -1044,7 +1044,7 @@ class TestGoalEntityMatches(_VisionAPITestCase):
# A token with scanner and recording scopes but not survey:read must not learn a survey's
# name or id through the draft. RBAC alone would allow it; the scope gate is what stops it.
self._survey("Pricing feedback")
- Action.objects.create(team=self.team, name="Pricing feedback click")
+ create_action(team=self.team, name="Pricing feedback click")
Cohort.objects.create(team=self.team, name="Pricing feedback cohort")
matches = _goal_entity_matches(
@@ -1081,7 +1081,7 @@ class TestGoalEntityMatches(_VisionAPITestCase):
# the recordings query drops a cohort filter it cannot resolve, so the scan widens to every
# session while the rationale still describes an audience.
Cohort.objects.create(team=self.team, name="Power users", deleted=True)
- Action.objects.create(team=self.team, name="Power users click", deleted=True)
+ create_action(team=self.team, name="Power users click", deleted=True)
matches = _goal_entity_matches(self.team, "what do power users struggle with", _access_control(allow=True))
diff --git a/products/replay_vision/backend/tests/test_scanner_query.py b/products/replay_vision/backend/tests/test_scanner_query.py
index b64091cb8614..8d542cd5c8aa 100644
--- a/products/replay_vision/backend/tests/test_scanner_query.py
+++ b/products/replay_vision/backend/tests/test_scanner_query.py
@@ -4,7 +4,7 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.replay_vision.backend.scanner_query import (
MAX_QUERY_BYTES,
@@ -91,7 +91,7 @@ class TestChosenScope:
class TestUnresolvedReferences(BaseTest):
def test_names_the_references_a_scan_cannot_load(self):
- live_action = Action.objects.create(team=self.team, name="Completed checkout")
+ live_action = create_action(team=self.team, name="Completed checkout")
live_cohort = Cohort.objects.create(team=self.team, name="Paying customers")
deleted_cohort = Cohort.objects.create(team=self.team, name="Old customers", deleted=True)
query = {
diff --git a/products/signals/backend/scout_harness/profile/builders.py b/products/signals/backend/scout_harness/profile/builders.py
index c43503b8ad9e..e6c4c99820c2 100644
--- a/products/signals/backend/scout_harness/profile/builders.py
+++ b/products/signals/backend/scout_harness/profile/builders.py
@@ -49,7 +49,7 @@ from posthog.models.product_intent.product_intent import ProductIntent
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action_inventory
from products.alerts.backend.facade.destinations import redact_urls_in_name
from products.alerts.backend.models.alert import AlertConfiguration
from products.business_knowledge.backend.models.constants import SourceStatus
@@ -710,18 +710,16 @@ def _recent_actions(team: Team) -> dict[str, Any]:
this user behavior as a named thing"). Sort by `updated_at` so both new actions
and edits to step definitions surface.
"""
- qs = Action.objects.filter(team=team, deleted=False)
- total = qs.count()
- recent = qs.order_by("-updated_at")[:RECENT_ENTITY_LIMIT].values("id", "name", "updated_at")
+ inventory = get_action_inventory(team_id=team.pk, recent_limit=RECENT_ENTITY_LIMIT)
return {
- "total_count": total,
+ "total_count": inventory.total_count,
"recent": [
{
- "id": row["id"],
- "name": (row["name"] or "").strip(),
- "updated_at": row["updated_at"].isoformat() if row["updated_at"] else None,
+ "id": entry.id,
+ "name": (entry.name or "").strip(),
+ "updated_at": entry.updated_at.isoformat() if entry.updated_at else None,
}
- for row in recent
+ for entry in inventory.recent
],
}
diff --git a/products/signals/backend/test/test_scout_harness_profile.py b/products/signals/backend/test/test_scout_harness_profile.py
index fae1a3bde97e..2f9578a579d0 100644
--- a/products/signals/backend/test/test_scout_harness_profile.py
+++ b/products/signals/backend/test/test_scout_harness_profile.py
@@ -30,7 +30,7 @@ from posthog.models.product_intent.product_intent import ProductIntent
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.alerts.backend.models.alert import AlertConfiguration
from products.business_knowledge.backend.models.knowledge_chunk import KnowledgeChunk
from products.business_knowledge.backend.models.knowledge_document import KnowledgeDocument
@@ -828,22 +828,22 @@ class TestRecentCohorts(BaseTest):
class TestRecentActions(BaseTest):
def test_orders_by_updated_at_desc(self) -> None:
- a = Action.objects.create(team=self.team, name="a", created_by=self.user)
- Action.objects.filter(id=a.id).update(updated_at=timezone.now() - timedelta(days=1))
- Action.objects.create(team=self.team, name="b", created_by=self.user)
+ a = create_action(team=self.team, name="a", created_by=self.user)
+ update_action(a, updated_at=timezone.now() - timedelta(days=1))
+ create_action(team=self.team, name="b", created_by=self.user)
result = _recent_actions(self.team)
assert [r["name"] for r in result["recent"]] == ["b", "a"]
def test_excludes_deleted(self) -> None:
- Action.objects.create(team=self.team, name="kept", created_by=self.user)
- Action.objects.create(team=self.team, name="gone", deleted=True, created_by=self.user)
+ create_action(team=self.team, name="kept", created_by=self.user)
+ create_action(team=self.team, name="gone", deleted=True, created_by=self.user)
result = _recent_actions(self.team)
assert result["total_count"] == 1
assert result["recent"][0]["name"] == "kept"
def test_team_isolated(self) -> None:
other = self.organization.teams.create(name="other")
- Action.objects.create(team=other, name="x", created_by=self.user)
+ create_action(team=other, name="x", created_by=self.user)
result = _recent_actions(self.team)
assert result["total_count"] == 0
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 3415c2af76ef..fbc46dd7e089 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -40,7 +40,7 @@ from posthog.temporal.oauth import (
from products.access_control.backend.facade.contracts import PropertyAccessLevel
from products.access_control.backend.models.access_control import AccessControl
from products.access_control.backend.models.property_access_control import PropertyAccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.signals.backend.artefact_schemas import (
ChannelAssignment,
@@ -546,7 +546,7 @@ class TestSignalReportListAPI(APIBaseTest):
def test_action_restricted_member_cannot_read_metric_snapshot_or_definition(self) -> None:
self._enable_feature(AvailableFeature.ACCESS_CONTROL)
- action = Action.objects.create(team=self.team, name="Restricted action")
+ action = create_action(team=self.team, name="Restricted action")
AccessControl.objects.create(
team=self.team,
resource="action",
@@ -574,7 +574,7 @@ class TestSignalReportListAPI(APIBaseTest):
def test_queryless_snapshot_is_redacted_when_action_provenance_cannot_be_proven(self) -> None:
self._enable_feature(AvailableFeature.ACCESS_CONTROL)
- action = Action.objects.create(team=self.team, name="Restricted action")
+ action = create_action(team=self.team, name="Restricted action")
AccessControl.objects.create(
team=self.team,
resource="action",
@@ -670,7 +670,7 @@ class TestSignalReportListAPI(APIBaseTest):
assert detail_metric["query"] is None
def test_task_token_cannot_read_action_metric_without_action_scope(self) -> None:
- action = Action.objects.create(team=self.team, name="Scoped action")
+ action = create_action(team=self.team, name="Scoped action")
metric = self._affected_users_metric(series={"kind": "ActionsNode", "id": action.id, "math": "dau"})
report = self._create_report(metrics=[metric])
authenticate_as_sandbox_token(self, scopes=["task:read", "query:read"])
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index 625f364ae193..0bbe6706600d 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -71,8 +71,8 @@ from products.access_control.backend.presentation.access_control import (
AccessControlViewSetMixin,
UserAccessControlSerializerMixin,
)
-from products.actions.backend.api.action import ActionSerializer, ActionStepJSONSerializer
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import existing_action_ids, get_actions
+from products.actions.backend.presentation.views.action import ActionSerializer, ActionStepJSONSerializer
from products.approvals.backend.exceptions import ApprovalRequired
from products.approvals.backend.presentation.mixins import ApprovalHandlingMixin
from products.approvals.backend.transactions import gated_atomic
@@ -1318,9 +1318,9 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
if action_ids is None or not all(0 < action_id < 2**63 for action_id in action_ids):
raise serializers.ValidationError("Each action in the survey conditions needs a valid id.")
- added_actions = Action.objects.filter(team__project_id=self.context["project_id"], id__in=action_ids)
if self.instance is not None:
- added_actions = added_actions.exclude(id__in=self.instance.actions.values("id"))
+ action_ids -= set(self.instance.actions.values_list("id", flat=True))
+ added_actions = get_actions(project_id=self.context["project_id"], action_ids=action_ids)
denied_ids = self.context["view"].user_access_control.denied_object_ids(
"action", [(str(action.id), action.team_id, action.created_by_id) for action in added_actions], "viewer"
)
@@ -2184,7 +2184,7 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
action_ids = (value.get("id") for value in values)
- instance.actions.set(Action.objects.filter(team__project_id=self.context["project_id"], id__in=action_ids))
+ instance.actions.set(existing_action_ids(project_id=self.context["project_id"], action_ids=action_ids))
instance.save()
def _should_survey_flags_be_active(self, instance: Survey) -> bool:
@@ -3715,11 +3715,16 @@ class _SurveyAPIActionStepSerializer(ActionStepJSONSerializer):
return fields
-class SurveyAPIActionSerializer(serializers.ModelSerializer):
- steps = _SurveyAPIActionStepSerializer(many=True, required=False)
+class SurveyAPIActionSerializer(serializers.Serializer):
+ id = serializers.IntegerField(read_only=True, help_text="ID of the action.")
+ name = serializers.CharField(read_only=True, allow_null=True, help_text="Name of the action, or null if unnamed.")
+ steps = _SurveyAPIActionStepSerializer(
+ many=True, read_only=True, help_text="Steps an event must match one of to match the action."
+ )
+ # Not read by DRF on a plain Serializer: get_survey_conditions_with_actions projects a stale stored
+ # actions blob down to these fields, so the public payload never carries more than the serializer would.
class Meta:
- model = Action
fields = [
"id",
"name",
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index bd808632a27c..0043a8683202 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -33,7 +33,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.test.persons import create_person
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
from products.cohorts.backend.models.cohort import Cohort
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -4820,7 +4820,7 @@ class TestSurveyQuestionValidationWithEnterpriseFeatures(APIBaseTest):
class TestSurveyWithActions(APIBaseTest):
def test_can_use_actions_with_properties(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="person subscribed",
steps_json=[
@@ -4900,13 +4900,13 @@ class TestSurveyWithActions(APIBaseTest):
assert value["name"] == "person subscribed"
def test_can_set_associated_actions(self):
- user_subscribed_action = Action.objects.create(
+ user_subscribed_action = create_action(
team=self.team,
name="user subscribed",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
)
- user_unsubscribed_action = Action.objects.create(
+ user_unsubscribed_action = create_action(
team=self.team,
name="user unsubscribed",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
@@ -4945,12 +4945,12 @@ class TestSurveyWithActions(APIBaseTest):
assert survey.actions.filter(name="user unsubscribed").exists()
def test_can_remove_associated_actions(self):
- user_subscribed_action = Action.objects.create(
+ user_subscribed_action = create_action(
team=self.team,
name="user subscribed",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
)
- Action.objects.create(
+ user_unsubscribed_action = create_action(
team=self.team,
name="user unsubscribed",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
@@ -4963,7 +4963,7 @@ class TestSurveyWithActions(APIBaseTest):
type="popover",
questions=[{"type": "open", "question": "Why's a hedgehog?"}],
)
- survey_with_actions.actions.set(Action.objects.filter(name__in=["user subscribed", "user unsubscribed"]))
+ survey_with_actions.actions.set([user_subscribed_action.id, user_unsubscribed_action.id])
survey_with_actions.save()
assert survey_with_actions.actions.filter(name="user unsubscribed").exists()
@@ -4999,7 +4999,7 @@ class TestSurveyWithActions(APIBaseTest):
"products.access_control.backend.facade.user_access_control.UserAccessControl.access_controls_supported", True
)
def test_linking_an_action_needs_viewer_access_to_it(self) -> None:
- restricted = Action.objects.create(team=self.team, name="restricted", steps_json=[{"event": "$pageview"}])
+ restricted = create_action(team=self.team, name="restricted", steps_json=[{"event": "$pageview"}])
AccessControl.objects.create(
team=self.team, resource="action", resource_id=str(restricted.id), access_level="none"
)
@@ -5007,7 +5007,7 @@ class TestSurveyWithActions(APIBaseTest):
stored = Survey.objects.create(
team=self.team, created_by=self.user, name="linked", type="popover", questions=questions
)
- stored.actions.set([restricted])
+ stored.actions.set([restricted.id])
conditions = {"actions": {"values": [{"name": "restricted", "id": restricted.id}]}}
self.client.force_login(self._create_user("[email protected]"))
@@ -5044,12 +5044,12 @@ class TestSurveyWithActions(APIBaseTest):
assert response.json()["attr"] == "conditions"
def test_can_clear_associated_actions(self):
- Action.objects.create(
+ user_subscribed_action = create_action(
team=self.team,
name="user subscribed",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
)
- Action.objects.create(
+ user_unsubscribed_action = create_action(
team=self.team,
name="user unsubscribed",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
@@ -5062,7 +5062,7 @@ class TestSurveyWithActions(APIBaseTest):
type="popover",
questions=[{"type": "open", "question": "Why's a hedgehog?"}],
)
- survey_with_actions.actions.set(Action.objects.filter(name__in=["user subscribed", "user unsubscribed"]))
+ survey_with_actions.actions.set([user_subscribed_action.id, user_unsubscribed_action.id])
survey_with_actions.save()
assert survey_with_actions.actions.filter(name="user subscribed").exists()
assert survey_with_actions.actions.filter(name="user unsubscribed").exists()
@@ -5094,7 +5094,7 @@ class TestSurveyWithActions(APIBaseTest):
assert len(survey.actions.all()) == 0
def test_update_without_conditions_keeps_associated_actions(self):
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="user subscribed",
steps_json=[{"event": "$pageview", "url": "docs", "url_matching": "contains"}],
@@ -5107,7 +5107,7 @@ class TestSurveyWithActions(APIBaseTest):
questions=[{"type": "open", "question": "Why's a hedgehog?"}],
conditions={"actions": {"values": [{"id": action.id}]}},
)
- survey_with_actions.actions.set([action])
+ survey_with_actions.actions.set([action.id])
response = self.client.patch(
f"/api/projects/{self.team.id}/surveys/{survey_with_actions.id}/",
@@ -5115,7 +5115,7 @@ class TestSurveyWithActions(APIBaseTest):
format="json",
)
assert response.status_code == status.HTTP_200_OK, response.json()
- assert list(Survey.objects.get(id=survey_with_actions.id).actions.all()) == [action]
+ assert list(Survey.objects.get(id=survey_with_actions.id).actions.values_list("id", flat=True)) == [action.id]
class TestGetSurveyConditionsActionSanitization(SimpleTestCase):
@@ -7138,7 +7138,7 @@ class TestSurveyBulkDuplication(APIBaseTest):
created_by=self.user,
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Test Action",
)
diff --git a/products/surveys/backend/models.py b/products/surveys/backend/models.py
index 62fbc0bf4027..5ba29265b890 100644
--- a/products/surveys/backend/models.py
+++ b/products/surveys/backend/models.py
@@ -19,8 +19,6 @@ from posthog.models.file_system.file_system_representation import FileSystemRepr
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
@@ -304,7 +302,7 @@ class Survey(FileSystemSyncMixin, RootTeamMixin, UUIDTModel):
# Not sealed: the resource transfer graph walks reverse descriptors, so hiding
# survey_set would silently drop the survey link from Action-rooted duplications
# (test_relation_fields_Action locks the field list).
- actions = models.ManyToManyField(Action)
+ actions = models.ManyToManyField("actions.Action")
@classmethod
def get_file_system_unfiled(cls, team: "Team", surface: str = DEFAULT_SURFACE) -> QuerySet["Survey"]:
diff --git a/products/web_analytics/backend/achievements/evaluators.py b/products/web_analytics/backend/achievements/evaluators.py
index ab6f26ed432b..d551d95b6102 100644
--- a/products/web_analytics/backend/achievements/evaluators.py
+++ b/products/web_analytics/backend/achievements/evaluators.py
@@ -1,7 +1,7 @@
import json
import hashlib
from collections.abc import Callable
-from dataclasses import dataclass, replace
+from dataclasses import asdict, dataclass, replace
from datetime import UTC, date, datetime, time, timedelta
from time import monotonic
@@ -20,7 +20,8 @@ from posthog.exceptions import ClickHouseEstimatedQueryExecutionTimeTooLong, Cli
from posthog.models.team.team import Team
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import list_top_actions
+from products.actions.backend.facade.contracts import Action
from products.web_analytics.backend.achievements.definitions import STREAK_ARM_WEEKLY, TRACKS, TrackKey
from products.web_analytics.backend.achievements.query_concurrency import achievement_query_scope
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import test_account_filter_expr
@@ -334,7 +335,12 @@ def _action_event_filter_expr(actions: list[Action]) -> ast.Expr:
def _action_fingerprints(actions: list[Action]) -> list[list[object]]:
return [
- [action.id, hashlib.sha256(json.dumps(action.steps_json or [], sort_keys=True).encode()).hexdigest()[:16]]
+ [
+ action.id,
+ hashlib.sha256(json.dumps([asdict(step) for step in action.steps], sort_keys=True).encode()).hexdigest()[
+ :16
+ ],
+ ]
for action in actions
]
@@ -402,7 +408,10 @@ def _add_conversion_counts(
latest_inclusive: bool = False,
) -> bool:
chunk_daily: dict[str, list[int]] = {}
- for team in _project_environment_teams(ctx.team):
+ environment_teams = _project_environment_teams(ctx.team)
+ # Actions live on the project's root team, which is one of these, so compiling them reads no team again.
+ teams_by_id = {team.id: team for team in environment_teams}
+ for team in environment_teams:
query = parse_select(
"SELECT toDate(toTimeZone(timestamp, 'UTC')) AS day FROM events WHERE and({window}, {events}, {test}) GROUP BY day",
placeholders={
@@ -415,7 +424,10 @@ def _add_conversion_counts(
raise TypeError(f"evaluate_conversions: expected SelectQuery, got {type(query)}")
query.select = [
query.select[0],
- *(ast.Call(name="countIf", args=[action_to_expr(action)]) for action in actions),
+ *(
+ ast.Call(name="countIf", args=[action_to_expr(action, team=teams_by_id.get(action.team_id))])
+ for action in actions
+ ),
]
# Future slices can group more than the default 100 days; the largest bounded slice is 50 years.
query.limit = ast.Constant(value=MAX_SELECT_RETURNED_ROWS)
@@ -605,11 +617,7 @@ def _advance_conversion_bootstrap(
def evaluate_conversions(ctx: EvalContext, prior: PriorProgress) -> TrackEvaluation:
- actions = list(
- Action.objects.filter(team__project_id=ctx.team.project_id, deleted=False)
- .select_related("team")
- .order_by("pinned_at", "-last_calculated_at")[:5]
- )
+ actions = list_top_actions(project_id=ctx.team.project_id, limit=5)
if not actions:
return TrackEvaluation(value=0, checkpoint={})
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py
index 8d731cdbd614..10a261a95d38 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py
@@ -15,7 +15,7 @@ from posthog.schema import (
from posthog.models.utils import uuid7
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner
@@ -318,7 +318,7 @@ class TestWebAnalyticsCohortFilter(ClickhouseTestMixin, APIBaseTest):
)
flush_persons_and_events()
- Action.objects.create(
+ create_action(
team=self.team,
name="Visit Page 1",
steps_json=[{"event": "$pageview", "url": "/page1", "url_matching": "contains"}],
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals.py
index acd7d8991568..3141ac993809 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_goals.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals.py
@@ -27,7 +27,7 @@ from posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE
from posthog.models.utils import uuid7
from posthog.test.persons import add_cohort_members
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action, delete_action
from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner
@@ -85,7 +85,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def _create_actions(self):
with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
- a0 = Action.objects.create(
+ a0 = create_action(
team=self.team,
name="Clicked Pay",
steps_json=[
@@ -97,7 +97,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
],
last_calculated_at=self.EVENT_TIMESTAMP, # oldest
)
- a1 = Action.objects.create(
+ a1 = create_action(
team=self.team,
name="Contacted Sales",
steps_json=[
@@ -110,7 +110,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
pinned_at=self.QUERY_TIMESTAMP,
last_calculated_at=self.QUERY_TIMESTAMP,
)
- a2 = Action.objects.create(
+ a2 = create_action(
team=self.team,
name="Visited Web Analytics",
steps_json=[
@@ -262,7 +262,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
p2, s2 = self._create_person()
self._visit_web_analytics(p1, s1)
self._click_pay(p2, s2)
- actions[0].delete()
+ delete_action(actions[0])
results = self._run_web_goals_query("2024-11-01", None).results
assert results == [
["Contacted Sales", (0, 0), (0, 0), (0, 0)],
@@ -293,7 +293,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
# Create multiple actions to generate complex query
with time_machine.travel(self.QUERY_TIMESTAMP, tick=False):
- Action.objects.create(
+ create_action(
team=self.team,
name="Test Action 1",
steps_json=[
@@ -314,7 +314,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
last_calculated_at=self.QUERY_TIMESTAMP,
)
- Action.objects.create(
+ create_action(
team=self.team,
name="Test Action 2",
steps_json=[
@@ -327,7 +327,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
last_calculated_at=self.QUERY_TIMESTAMP,
)
- Action.objects.create(
+ create_action(
team=self.team,
name="Test Action 3",
steps_json=[
@@ -341,7 +341,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
last_calculated_at=self.QUERY_TIMESTAMP,
)
- Action.objects.create(
+ create_action(
team=self.team,
name="Test Action 4",
steps_json=[
@@ -356,7 +356,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):
last_calculated_at=self.QUERY_TIMESTAMP,
)
- Action.objects.create(
+ create_action(
team=self.team,
name="Test Action 5",
steps_json=[
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py
index aa10e120c73f..5744109c9266 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py
@@ -19,7 +19,9 @@ from posthog.schema import (
from posthog.models.utils import uuid7
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import list_actions
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action, delete_action
from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner
from products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute import can_use_lazy_precompute
@@ -30,7 +32,8 @@ class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
def setUp(self) -> None:
super().setUp()
PreaggregationJob.objects.filter(team_id=self.team.pk).delete()
- Action.objects.filter(team__project_id=self.team.project_id).delete()
+ for action in list_actions(project_id=self.team.project_id, include_deleted=True):
+ delete_action(action)
def _enable_lazy(self):
# Same flag the paths/frustration tests patch — the gate evaluates the
@@ -41,7 +44,7 @@ class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
)
def _create_action(self, name: str, event: str = "$pageview") -> Action:
- return Action.objects.create(
+ return create_action(
team=self.team,
name=name,
steps_json=[{"event": event}],
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
index 18d67c3e8a2b..753281c9e89a 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
@@ -48,7 +48,8 @@ from posthog.models import Element, Team
from posthog.models.utils import uuid7
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
from products.web_analytics.backend.hogql_queries.test.first_pageview_attribution_test_base import (
@@ -185,7 +186,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
"bounce rate",
]
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[
@@ -214,7 +215,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
action = None
if with_conversion_goal:
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[{"event": "$pageview"}],
@@ -514,7 +515,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
]
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[
@@ -548,7 +549,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
]
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[
@@ -593,9 +594,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
properties = [EventPropertyFilter(key="plan", value="paid", operator=PropertyOperator.EXACT)]
goal: ActionConversionGoal | CustomEventConversionGoal
if use_action:
- action = Action.objects.create(
- team=self.team, name="Customer created", steps_json=[{"event": "customer_created"}]
- )
+ action = create_action(team=self.team, name="Customer created", steps_json=[{"event": "customer_created"}])
goal = ActionConversionGoal(actionId=action.id, properties=properties)
else:
goal = CustomEventConversionGoal(customEventName="customer_created", properties=properties)
@@ -661,7 +660,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
self._create_events([("p1", [("2023-12-01", s1, "https://www.example.com/foo")])])
self._create_events([("p1", [("2023-12-01", s1)])], event="custom_event")
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Did Custom Event",
steps_json=[
@@ -695,7 +694,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
event="$autocapture",
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Paid $10",
steps_json=[
@@ -746,7 +745,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
]
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[
@@ -805,7 +804,7 @@ class TestWebOverviewQueryRunner(FirstPageviewAttributionTestMixin, ClickhouseTe
]
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
index 90ad2c8c63b5..45f5f78ff4ec 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
@@ -45,7 +45,8 @@ from posthog.hogql.printer import prepare_and_print_ast
from posthog.models import Element
from posthog.models.utils import uuid7
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action
from products.cohorts.backend.models.cohort import Cohort
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
from products.web_analytics.backend.hogql_queries.test.first_pageview_attribution_test_base import (
@@ -1739,7 +1740,7 @@ class TestWebStatsTableQueryRunner(
]
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Bar",
steps_json=[{"event": "$pageview", "url": "https://www.example.com/bar", "url_matching": "regex"}],
@@ -1771,7 +1772,7 @@ class TestWebStatsTableQueryRunner(
]
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[
@@ -1838,7 +1839,7 @@ class TestWebStatsTableQueryRunner(
event="custom_event",
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Did Custom Event",
steps_json=[
@@ -1875,7 +1876,7 @@ class TestWebStatsTableQueryRunner(
event="$autocapture",
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Paid $10",
steps_json=[
@@ -1930,7 +1931,7 @@ class TestWebStatsTableQueryRunner(
]
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[
@@ -2142,7 +2143,7 @@ class TestWebStatsTableQueryRunner(
]
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[{"event": "$pageview", "url": "/foo", "url_matching": "regex"}],
@@ -2181,7 +2182,7 @@ class TestWebStatsTableQueryRunner(
]
)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Visited Foo",
steps_json=[{"event": "$pageview", "url": "/foo", "url_matching": "regex"}],
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py
index 5caac76f0209..9af86217a7b6 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py
@@ -21,7 +21,7 @@ from posthog.clickhouse.client.execute import sync_execute
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
+from products.actions.backend.facade.testing import create_action
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_base import (
WebAnalyticsPreAggregatedTestBase,
@@ -71,7 +71,7 @@ class TestWebStatsTablePreAggregatedConversions(WebAnalyticsPreAggregatedTestBas
self._setup_test_data(user_prefix="hybrid")
# Create a conversion action
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Converted",
steps_json=[
@@ -268,7 +268,7 @@ class TestWebStatsTablePreAggregatedConversions(WebAnalyticsPreAggregatedTestBas
try:
self._setup_test_data(user_prefix="bounce")
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="Converted",
steps_json=[
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
index 88c2b4aab65e..ca6dffbda480 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
@@ -47,7 +47,8 @@ from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPr
from posthog.models import User
from products.access_control.backend.facade.user_access_control import UserAccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import get_action
+from products.actions.backend.facade.contracts import ActionNotFound
from products.web_analytics.backend.hogql_queries.first_pageview_attribution import first_pageview_session_filter_expr
from products.web_analytics.backend.hogql_queries.first_pageview_flag import (
evaluate_team_rollout_flag,
@@ -559,10 +560,8 @@ WHERE and(
def conversion_goal_expr(self) -> Optional[ast.Expr]:
if isinstance(self.query.conversionGoal, ActionConversionGoal):
try:
- action = Action.objects.get(
- pk=self.query.conversionGoal.actionId, team__project_id=self.team.project_id
- )
- except Action.DoesNotExist:
+ action = get_action(action_id=int(self.query.conversionGoal.actionId), project_id=self.team.project_id)
+ except ActionNotFound:
raise QueryError(
f"Conversion goal action with id={self.query.conversionGoal.actionId} not found in this project."
)
diff --git a/products/web_analytics/backend/hogql_queries/web_goals.py b/products/web_analytics/backend/hogql_queries/web_goals.py
index f959201ebe7a..584eb7f2f190 100644
--- a/products/web_analytics/backend/hogql_queries/web_goals.py
+++ b/products/web_analytics/backend/hogql_queries/web_goals.py
@@ -14,7 +14,7 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.property import action_to_expr, get_property_type, property_to_expr
from posthog.hogql.query import execute_hogql_query
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import list_top_actions
from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
from products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute import (
can_use_lazy_precompute,
@@ -43,9 +43,7 @@ class WebGoalsQueryRunner(WebAnalyticsQueryRunner[WebGoalsQueryResponse]):
def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
with self.timings.measure("actions"):
- actions = Action.objects.filter(team__project_id=self.team.project_id, deleted=False).order_by(
- "pinned_at", "-last_calculated_at"
- )[:5]
+ actions = list_top_actions(project_id=self.team.project_id, limit=5)
if not actions:
raise NoActionsError("No actions found")
@@ -58,7 +56,7 @@ class WebGoalsQueryRunner(WebAnalyticsQueryRunner[WebGoalsQueryResponse]):
outer_aliases: list[ast.Expr] = []
action_exprs: list[ast.Expr] = []
for n, action in enumerate(actions):
- expr = action_to_expr(action)
+ expr = action_to_expr(action, team=self.team)
action_exprs.append(expr)
# Current/previous count
diff --git a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
index cd1949268c8f..61631c4fd111 100644
--- a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
@@ -10,7 +10,7 @@ via `web_lazy_precompute_common`. The precomputed table stores one row per
counts plus unique converting persons.
The action set (the top-5 actions returned by
-`Action.objects…order_by('pinned_at', '-last_calculated_at')[:5]`) is part
+`list_top_actions(project_id=..., limit=5)`) is part
of the INSERT AST and therefore the lazy_computation cache key — a different
top-5 set yields a different job_id, so the runner's hard `[:5]` slice is
mirrored without further coordination.
@@ -33,7 +33,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import list_top_actions
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
LazyComputationResult,
LazyComputationTable,
@@ -53,6 +53,8 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imp
)
if TYPE_CHECKING:
+ from posthog.models.team import Team
+
from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner
logger = structlog.get_logger(__name__)
@@ -60,12 +62,12 @@ logger = structlog.get_logger(__name__)
_FAMILY = "web_goals"
-# Sentinel action_id used for the per-hour denominator row. Real Django
-# `Action.id` values are positive auto-increment integers, so -1 is safe.
+# Sentinel action_id used for the per-hour denominator row. Real action ids
+# are positive auto-increment integers, so -1 is safe.
DENOMINATOR_ACTION_ID = -1
# Maximum number of actions the precompute will cover. Matches the runner's
-# hard `Action.objects…[:5]` slice exactly — precomputing more would be
+# hard limit of 5 actions exactly — precomputing more would be
# wasted INSERT work the runner never reads. If the live UX ever expands
# beyond 5 actions, bump both this constant and the runner's slice together.
MAX_ACTIONS = 5
@@ -169,10 +171,7 @@ def _select_actions(runner: "WebGoalsQueryRunner") -> list:
cached = getattr(runner, _RUNNER_ACTIONS_CACHE_ATTR, None)
if cached is not None:
return cached
- qs = Action.objects.filter(team__project_id=runner.team.project_id, deleted=False).order_by(
- "pinned_at", "-last_calculated_at"
- )[:MAX_ACTIONS]
- fetched = list(qs)
+ fetched = list_top_actions(project_id=runner.team.project_id, limit=MAX_ACTIONS)
setattr(runner, _RUNNER_ACTIONS_CACHE_ATTR, fetched)
return fetched
@@ -181,11 +180,11 @@ def _events_session_id_expr(runner: "WebGoalsQueryRunner") -> ast.Expr:
return runner.events_session_property
-def _action_or_expr(actions: Sequence) -> ast.Expr:
+def _action_or_expr(actions: Sequence, team: "Team") -> ast.Expr:
"""Build `Or(action_to_expr(a) for a in actions)` — gates the events scan
to events that can possibly contribute to any of the actions, plus
`$pageview`/`$screen` which always anchor the session."""
- return ast.Or(exprs=[action_to_expr(a) for a in actions])
+ return ast.Or(exprs=[action_to_expr(a, team=team) for a in actions])
def _build_insert_query(actions: Sequence) -> str:
@@ -289,7 +288,7 @@ def ensure_web_goals_precomputed(
) -> LazyComputationResult:
placeholders: dict[str, ast.Expr] = {
"events_session_id": _events_session_id_expr(runner),
- "action_or_expr": _action_or_expr(actions),
+ "action_or_expr": _action_or_expr(actions, runner.team),
"user_filter": host_filter_expr(runner.query.properties or [], team=runner.team),
"test_account_filter": test_account_filter_expr(
test_account_filters=runner._test_account_filters, team=runner.team
@@ -297,7 +296,7 @@ def ensure_web_goals_precomputed(
"pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),
}
for n, action in enumerate(actions):
- placeholders[f"action_{n}_expr"] = action_to_expr(action)
+ placeholders[f"action_{n}_expr"] = action_to_expr(action, team=runner.team)
placeholders[f"action_{n}_id"] = ast.Constant(value=int(action.id))
return web_ensure_precomputed(
@@ -388,7 +387,7 @@ def execute_lazy_precomputed_read(runner: "WebGoalsQueryRunner") -> Optional[dic
Output shape:
{
- "actions": [Action, ...], # top-N in order
+ "actions": [Action, ...], # top-N in order, as actions facade contracts
"denominator": {"current": int, "previous": int},
"per_action": {
action_id: {
diff --git a/products/web_analytics/backend/test/test_achievements_evaluators.py b/products/web_analytics/backend/test/test_achievements_evaluators.py
index ef5fd5948de0..30c2b6fced62 100644
--- a/products/web_analytics/backend/test/test_achievements_evaluators.py
+++ b/products/web_analytics/backend/test/test_achievements_evaluators.py
@@ -16,7 +16,8 @@ from posthog.exceptions import ClickHouseEstimatedQueryExecutionTimeTooLong, Cli
from posthog.models import Element, Team, User
from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, filter_through_warehouse_join
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.contracts import Action
+from products.actions.backend.facade.testing import create_action, update_action
from products.web_analytics.backend.achievements.definitions import STREAK_ARM_DAILY, STREAK_ARM_WEEKLY
from products.web_analytics.backend.achievements.evaluators import (
INGESTION_LAG,
@@ -92,7 +93,7 @@ class TestTeamEvaluators(ClickhouseTestMixin, APIBaseTest):
return EvalContext(team=self.team, user=None, today=date.today(), arm=None)
def _pay_action(self, event: str | None) -> Action:
- return Action.objects.create(
+ return create_action(
team=self.team,
name="Clicked Pay",
steps_json=[{"event": event, "tag_name": "button", "text": "Pay $10"}],
@@ -576,8 +577,7 @@ class TestTeamEvaluators(ClickhouseTestMixin, APIBaseTest):
assert prior_checkpoint is not None
actions = prior_checkpoint["actions"]
if change == "edited_steps":
- action.steps_json = [{"event": "$autocapture", "text": "Pay $10"}]
- action.save()
+ update_action(action, steps_json=[{"event": "$autocapture", "text": "Pay $10"}])
elif change == "other_actions":
actions = [[action.id + 1, "0"]]
now = timezone.now()
diff --git a/products/web_analytics/backend/test/test_achievements_query_concurrency.py b/products/web_analytics/backend/test/test_achievements_query_concurrency.py
index 91bc09464067..aa5ce058bba8 100644
--- a/products/web_analytics/backend/test/test_achievements_query_concurrency.py
+++ b/products/web_analytics/backend/test/test_achievements_query_concurrency.py
@@ -93,14 +93,11 @@ class TestAchievementQueryConcurrency(SimpleTestCase):
def test_conversions_use_the_same_budget_as_pageviews(self) -> None:
self._fill_budget()
with (
- patch.object(evaluators.Action, "objects") as actions,
+ patch.object(evaluators, "list_top_actions", return_value=[Mock(id=1, team_id=self.team.id, steps=())]),
patch.object(evaluators, "_project_environment_teams", return_value=[self.team]),
patch.object(evaluators, "action_to_expr", return_value=evaluators.ast.Constant(value=True)),
patch.object(evaluators, "execute_hogql_query") as execute,
):
- actions.filter.return_value.select_related.return_value.order_by.return_value.__getitem__.return_value = [
- Mock(id=1, steps_json=[])
- ]
with self.assertRaises(ConcurrencyLimitExceeded):
evaluators.evaluate_conversions(self.ctx, self.prior)
execute.assert_not_called()
diff --git a/products/web_analytics/backend/test/test_weekly_digest.py b/products/web_analytics/backend/test/test_weekly_digest.py
index 82b0b4b79f71..2f44dfefe90e 100644
--- a/products/web_analytics/backend/test/test_weekly_digest.py
+++ b/products/web_analytics/backend/test/test_weekly_digest.py
@@ -25,7 +25,7 @@ from posthog.models import Team
from posthog.models.utils import uuid7
from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, filter_through_warehouse_join
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.web_analytics.backend.hogql_queries.web_goals import NoActionsError
from products.web_analytics.backend.weekly_digest import (
_default_overview,
@@ -411,7 +411,7 @@ class TestGetGoalsForTeam(ClickhouseTestMixin, APIBaseTest):
def test_returns_goals_with_conversions(self):
with time_machine.travel(QUERY_TIMESTAMP, tick=False):
- Action.objects.create(
+ create_action(
team=self.team,
name="Signed Up",
steps_json=[{"event": "signed_up"}],
@@ -437,7 +437,7 @@ class TestGetGoalsForTeam(ClickhouseTestMixin, APIBaseTest):
@patch(WAREHOUSE_ACCESS_CONTROL_FLAG, new=Mock(return_value=True))
def test_userless_job_reads_an_action_filter_through_a_warehouse_join(self):
- Action.objects.create(
+ create_action(
team=self.team,
name="Signed Up",
steps_json=[{"event": "signed_up", "properties": [filter_through_warehouse_join(self.team)]}],
diff --git a/products/workflows/backend/apps.py b/products/workflows/backend/apps.py
index 1bb42f8fd085..d38c5c19b58e 100644
--- a/products/workflows/backend/apps.py
+++ b/products/workflows/backend/apps.py
@@ -7,4 +7,9 @@ class WorkflowsConfig(AppConfig):
label = "workflows"
def ready(self) -> None:
+ from products.actions.backend.facade.api import on_action_saved # noqa: PLC0415
from products.workflows.backend import receivers # noqa: F401, PLC0415 — registers signal receivers
+ from products.workflows.backend.models.hog_flow.hog_flow import action_saved_for_hog_flows # noqa: PLC0415
+
+ # Compiled filters embed each action's matcher, so they must be rebuilt when an action is saved.
+ on_action_saved(action_saved_for_hog_flows, dispatch_uid="workflows.hog_flows.action_saved")
diff --git a/products/workflows/backend/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.py
index 080c9e651b90..f6ece23e020a 100644
--- a/products/workflows/backend/models/hog_flow/hog_flow.py
+++ b/products/workflows/backend/models/hog_flow/hog_flow.py
@@ -17,7 +17,7 @@ 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
+from products.actions.backend.facade.contracts import ActionSaved
from products.workflows.backend.facade.enums import (
HogFlowEmailSendingPausedBy,
HogFlowExitCondition,
@@ -407,11 +407,10 @@ def hog_flow_deleted(sender, instance: HogFlow, **kwargs):
transaction.on_commit(lambda: _reload_batch_on_workers(team_id, [hog_flow_id]))
-@receiver(post_save, sender=Action)
-def action_saved_for_hog_flows(sender, instance: Action, created, **kwargs):
+def action_saved_for_hog_flows(event: ActionSaved) -> None:
from products.workflows.backend.tasks.hog_flows import refresh_affected_hog_flows # noqa: PLC0415
- refresh_affected_hog_flows.delay(action_id=instance.id)
+ refresh_affected_hog_flows.delay(action_id=event.action_id)
@receiver(post_save, sender=Team)
diff --git a/products/workflows/backend/tasks/hog_flows.py b/products/workflows/backend/tasks/hog_flows.py
index 26404602fd92..6a947ad4466f 100644
--- a/products/workflows/backend/tasks/hog_flows.py
+++ b/products/workflows/backend/tasks/hog_flows.py
@@ -15,7 +15,8 @@ from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
from posthog.utils import get_instance_region
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.api import find_action_team_id
+from products.actions.backend.facade.contracts import ActionNotFound
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
logger = get_logger(__name__)
@@ -33,12 +34,13 @@ def refresh_affected_hog_flows(team_id: Optional[int] = None, action_id: Optiona
affected_hog_flows: list[HogFlow] = []
if action_id:
- action = Action.objects.get(id=action_id)
- team_id = action.team_id
+ team_id = find_action_team_id(action_id=action_id)
+ if team_id is None:
+ raise ActionNotFound(f"Action {action_id} does not exist")
# Find hog flows that reference this action in their trigger filters
affected_hog_flows = list(
HogFlow.objects.select_related("team")
- .filter(team_id=action.team_id, status="active")
+ .filter(team_id=team_id, status="active")
.filter(trigger__contains={"actions": [{"id": str(action_id)}]})
)
elif team_id:
diff --git a/products/workflows/backend/test/test_hog_flow.py b/products/workflows/backend/test/test_hog_flow.py
index a986119621e9..d27462b007dc 100644
--- a/products/workflows/backend/test/test_hog_flow.py
+++ b/products/workflows/backend/test/test_hog_flow.py
@@ -10,7 +10,7 @@ from redis.exceptions import RedisError
from posthog.models.user import User
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow, defer_hog_flow_reloads
REPORT_CREATED = "products.workflows.backend.tasks.hog_flows.report_workflow_created.delay"
@@ -144,7 +144,7 @@ class TestHogFlow(TestCase):
@patch("products.workflows.backend.tasks.hog_flows.refresh_affected_hog_flows.delay")
def test_action_saved_receiver(self, mock_refresh):
- action = Action.objects.create(team=self.team, name="Test Action")
+ action = create_action(team=self.team, name="Test Action")
mock_refresh.assert_called_once_with(action_id=action.id)
@patch("products.workflows.backend.tasks.hog_flows.refresh_affected_hog_flows.delay")
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index 869112244d3c..26eaa9ee310a 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -32,7 +32,7 @@ from posthog.test.fixtures import create_app_metric2
from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
from products.cdp.backend.filters import RUNTIME_CONTRACT
from products.cdp.backend.flag_gated_templates import gated_template_enabled
@@ -2248,7 +2248,7 @@ class TestHogFlowAPI(APIBaseTest):
def test_hog_flow_conditional_branch_validates_cohorts_nested_in_action_filters(self, _mock_flag):
eligible = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
static_cohort = Cohort.objects.create(team=self.team, name="static-cohort", is_static=True)
- action = Action.objects.create(team=self.team, name="Converted", steps_json=[{"event": "converted"}])
+ action = create_action(team=self.team, name="Converted", steps_json=[{"event": "converted"}])
filters = {
"properties": [{"key": "id", "type": "cohort", "value": eligible.id}],
"actions": [
@@ -2537,7 +2537,7 @@ class TestHogFlowAPI(APIBaseTest):
def test_hog_flow_rejects_ineligible_cohorts_inside_referenced_actions(self, _mock_flag):
eligible = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
static_cohort = Cohort.objects.create(team=self.team, name="static-in-action", is_static=True)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="action with cohort step",
steps_json=[
@@ -2560,7 +2560,7 @@ class TestHogFlowAPI(APIBaseTest):
@patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
def test_hog_flow_compiles_eligible_cohort_referenced_only_through_an_action(self, _mock_flag):
eligible = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
- action = Action.objects.create(
+ action = create_action(
team=self.team,
name="action with eligible cohort step",
steps_json=[{"event": "$pageview", "properties": [{"key": "id", "type": "cohort", "value": eligible.id}]}],
@@ -3012,7 +3012,7 @@ class TestHogFlowAPI(APIBaseTest):
# An "events to wait for" entry can target a PostHog Action instead of an event: filters.actions
# is set and filters.events is empty. That is a real wait and must be kept (and its bytecode
# compiled), while a truly-empty entry alongside it is still dropped.
- action = Action.objects.create(team=self.team, name="Played with calculator", steps_json=[{"event": "calc"}])
+ action = create_action(team=self.team, name="Played with calculator", steps_json=[{"event": "calc"}])
trigger_action = {
"id": "trigger_node",
@@ -3108,7 +3108,7 @@ class TestHogFlowAPI(APIBaseTest):
def test_hog_flow_conversion_drops_empty_keeps_action_event(self):
# Same always-true guard as wait_until: a conversion "events" entry targeting nothing is
# dropped (it would convert on every event), while an action-based entry is kept and compiled.
- action = Action.objects.create(team=self.team, name="Converted via action", steps_json=[{"event": "converted"}])
+ action = create_action(team=self.team, name="Converted via action", steps_json=[{"event": "converted"}])
trigger_action = {
"id": "trigger_node",
"name": "trigger_1",
diff --git a/products/workflows/backend/tests/api/test_hog_flow_access_control.py b/products/workflows/backend/tests/api/test_hog_flow_access_control.py
index 2a57bd864d7a..57eb725d49e8 100644
--- a/products/workflows/backend/tests/api/test_hog_flow_access_control.py
+++ b/products/workflows/backend/tests/api/test_hog_flow_access_control.py
@@ -13,7 +13,7 @@ from posthog.models.user import User
from products.access_control.backend.facade.user_access_control import ACCESS_CONTROL_RESOURCES, model_to_resource
from products.access_control.backend.models.access_control import AccessControl
-from products.actions.backend.models.action import Action
+from products.actions.backend.facade.testing import create_action
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule
@@ -175,7 +175,7 @@ class TestHogFlowAccessControl(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand([("trigger",), ("conversion",)])
def test_action_reference_needs_viewer_access_unless_already_used(self, placement: str):
- action = Action.objects.create(
+ action = create_action(
team=self.team, name="restricted", steps_json=[{"event": "$pageview"}], created_by=self.user
)
self._create_access_control(self.editor_user, access_level="editor")
diff --git a/pyproject.toml b/pyproject.toml
index db68689bf25b..82fa7142edd0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -810,6 +810,14 @@ ignore_imports = [
"products.access_control.backend.presentation.access_control_settings -> products.access_control.backend.models.access_control",
"products.access_control.backend.presentation.access_control_settings -> products.access_control.backend.models.role",
"products.access_control.backend.presentation.role -> products.access_control.backend.models.role",
+ # TODO: actions presentation wave — the moved ActionViewSet is still a ModelViewSet over the Action model
+ # (tags, object access levels, folder placement), and its reference counts read cdp and cohorts rows
+ # directly. Thin it to parse -> facade -> serialize and delete each entry.
+ # backend:contract-check stays off until this list is empty.
+ "products.actions.backend.presentation.views.action -> products.actions.backend.models.action",
+ "products.actions.backend.presentation.views.action -> products.actions.backend.models.selector_match_change",
+ "products.actions.backend.presentation.views.action -> products.cdp.backend.models.hog_functions.hog_function",
+ "products.actions.backend.presentation.views.action -> products.cohorts.backend.models.cohort",
# TODO: signals presentation wave. The activity summary viewset reads its modes, limits and
# render types from backend/activity_summary/ directly. That directory has no __init__.py, so
# grimp cannot see these edges and only the AST surface check in `hogli product:lint` holds
@@ -837,7 +845,6 @@ allow_indirect_imports = true
ignore_imports = [
"products.**.backend.routes -> products.**.backend.presentation.**",
# TODO: views still registered from backend/api/ — move them into presentation/ and drop the line
- "products.actions.backend.routes -> products.actions.backend.api.action",
"products.ai_observability.backend.routes -> products.ai_observability.backend.api",
"products.analytics_platform.backend.routes -> products.analytics_platform.backend.api.precompute_debug",
"products.annotations.backend.routes -> products.annotations.backend.api.annotation",
diff --git a/tach.toml b/tach.toml
index 8fec22ae1020..6280a16dbf6d 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1230,7 +1230,7 @@ expose = [
"backend\\.routes.*",
]
from = [
- "products\\.(autoresearch|batch_exports|canvas|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|groups|managed_warehouse|mcp_analytics|mcp_store|messaging|metrics|notebooks|notifications|review_hog|streamlit_apps|subscriptions|tasks|tracing|visual_review|warehouse_sources|workflows)",
+ "products\\.(actions|autoresearch|batch_exports|canvas|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|groups|managed_warehouse|mcp_analytics|mcp_store|messaging|metrics|notebooks|notifications|review_hog|streamlit_apps|subscriptions|tasks|tracing|visual_review|warehouse_sources|workflows)",
]
# signals is not isolated, so it gets its own blocks instead of a place in the shared one above.