Skip to content

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

chore(insights): drop the legacy converter from replay entity nodes (#100097)

Thomas Obermüller05aa3968995e
diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.py
index 2d16d63d48e0..ac974f1b1621 100644
--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py
@@ -24,8 +24,7 @@ from posthog.hogql.query import execute_hogql_query, tracer
from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE, TREND_FILTER_TYPE_EVENTS
-from posthog.hogql_queries.legacy_compatibility.filter_to_query import MathAvailability, legacy_entity_to_node
-from posthog.models import Entity, EventProperty, Team
+from posthog.models import EventProperty, Team
from posthog.ph_client import feature_enabled_or_false
from posthog.session_recordings.queries.sub_queries.base_query import SessionRecordingsListingBaseQuery
from posthog.session_recordings.queries.sub_queries.group_key_resolver import resolved_group_key_expr
@@ -34,6 +33,7 @@ from posthog.session_recordings.queries.utils import (
NEGATIVE_OPERATORS,
SessionRecordingQueryResult,
_entity_to_expr,
+ _node_from_entity,
is_anonymous_cohort_fix_enabled,
is_cohort_property,
is_event_property,
@@ -81,11 +81,11 @@ def _event_session_id_field() -> ast.Field:
def get_negative_entity_properties(
- entities: list[EventsNode | ActionsNode | DataWarehouseNode | str],
+ entities: list[EventsNode | ActionsNode | DataWarehouseNode],
) -> list[AnyPropertyFilter]:
negative_props: list[AnyPropertyFilter] = []
for entity in entities:
- if isinstance(entity, DataWarehouseNode | str) or not entity.properties:
+ if isinstance(entity, DataWarehouseNode) or not entity.properties:
continue
for prop in entity.properties:
if is_negative_prop(prop):
@@ -137,12 +137,12 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
@staticmethod
def _event_predicates(
- entities: Iterable[EventsNode | ActionsNode | DataWarehouseNode | str], team: Team
+ entities: Iterable[EventsNode | ActionsNode | DataWarehouseNode], team: Team
) -> list[ast.Expr]:
event_exprs: list[ast.Expr] = []
for entity in entities:
- if isinstance(entity, DataWarehouseNode | str):
+ if isinstance(entity, DataWarehouseNode):
continue
# this is always _positive_ operations
@@ -799,9 +799,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
return bool(raw_entity.get("negation"))
@staticmethod
- def _entity_node(
- raw_entity: dict[str, Any], default_type: str
- ) -> EventsNode | ActionsNode | DataWarehouseNode | str:
+ def _entity_node(raw_entity: dict[str, Any], default_type: str) -> EventsNode | ActionsNode | DataWarehouseNode:
# RecordingsQuery accepts untyped entity dicts, and Entity rejects any type it does not
# know, so fall back to the type the source list implies.
entity = (
@@ -810,7 +808,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
else {**raw_entity, "type": default_type}
)
try:
- return legacy_entity_to_node(Entity(entity), True, MathAvailability.Unavailable)
+ return _node_from_entity(entity)
except ValueError as e:
# Entity and the node models raise plain ValueErrors for a dict they can't build from
# (pydantic's ValidationError subclasses it), and those escape as a 500. The dict is
@@ -839,7 +837,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
return self.action_entities + self.event_entities
@property
- def negated_entities(self) -> list[EventsNode | ActionsNode | DataWarehouseNode | str]:
+ def negated_entities(self) -> list[EventsNode | ActionsNode | DataWarehouseNode]:
# the legacy Entity class drops unknown keys, so negation is read off the raw dicts
return [
self._entity_node(e, TREND_FILTER_TYPE_ACTIONS)
diff --git a/posthog/session_recordings/queries/utils.py b/posthog/session_recordings/queries/utils.py
index 9daef51a17bd..9083e4df1f0e 100644
--- a/posthog/session_recordings/queries/utils.py
+++ b/posthog/session_recordings/queries/utils.py
@@ -1,5 +1,5 @@
import re
-from typing import NamedTuple
+from typing import Any, NamedTuple
import structlog
import posthoganalytics
@@ -8,6 +8,7 @@ from rest_framework.exceptions import ValidationError
from posthog.schema import (
ActionsNode,
CohortPropertyFilter,
+ DataWarehouseNode,
EventPropertyFilter,
EventsNode,
FilterLogicalOperator,
@@ -23,7 +24,9 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.property import action_to_expr
-from posthog.models import Team
+from posthog.constants import TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE
+from posthog.hogql_queries.legacy_compatibility.clean_properties import clean_entity_properties
+from posthog.models import Entity, Team
from posthog.types import AnyPropertyFilter
from products.actions.backend.models.action import Action
@@ -168,6 +171,30 @@ def poe_is_active(team: Team) -> bool:
return team.person_on_events_mode is not None and team.person_on_events_mode != PersonsOnEventsMode.DISABLED
+def _node_from_entity(raw_entity: dict[str, Any]) -> EventsNode | ActionsNode | DataWarehouseNode:
+ entity = Entity(raw_entity)
+ # Replay selects sessions and never aggregates, so the entity's math fields have no effect on
+ # the node and are left out.
+ shared: dict[str, Any] = {
+ "name": entity.name,
+ "custom_name": entity.custom_name,
+ "properties": clean_entity_properties(raw_entity.get("properties")),
+ }
+
+ if entity.type == TREND_FILTER_TYPE_ACTIONS:
+ return ActionsNode(id=entity.id, **shared)
+ if entity.type == TREND_FILTER_TYPE_DATA_WAREHOUSE:
+ return DataWarehouseNode(
+ id=entity.id,
+ id_field=entity.id_field,
+ distinct_id_field=entity.distinct_id_field,
+ timestamp_field=entity.timestamp_field,
+ table_name=entity.table_name,
+ **shared,
+ )
+ return EventsNode(event=entity.id, **shared)
+
+
def _entity_to_expr(entity: EventsNode | ActionsNode, team: Team) -> ast.Expr:
# KLUDGE: we should be able to use NodeKind.ActionsNode here but mypy :shrug:
if entity.kind == "ActionsNode":
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict_persons.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict_persons.py
index 486552666d65..6f3093dad39a 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict_persons.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_strict_persons.py
@@ -1,5 +1,4 @@
from datetime import datetime, timedelta
-from typing import Any, Optional, cast
from uuid import UUID
import time_machine
@@ -13,11 +12,8 @@ from posthog.test.base import (
from django.utils import timezone
-from posthog.schema import FunnelsQuery
+from posthog.schema import DateRange, EventsNode, FunnelsFilter, FunnelsQuery, IntervalType, StepOrderValue
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
-from posthog.models import Team
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from posthog.test.test_journeys import journeys_for
@@ -26,26 +22,16 @@ from products.product_analytics.backend.hogql_queries.funnels.test.test_funnel_p
FORMAT_TIME = "%Y-%m-%d 00:00:00"
-def get_actors_legacy_filters(
- filters: dict[str, Any],
- team: Team,
- funnel_step: Optional[int] = None,
- funnel_step_breakdown: Optional[str | float | list[str | float]] = None,
- funnel_trends_drop_off: Optional[bool] = None,
- funnel_trends_entrance_period_start: Optional[str] = None,
- offset: Optional[int] = None,
- include_recordings: bool = False,
-) -> list[list]:
- funnels_query = cast(FunnelsQuery, filter_to_query(filters))
- return get_actors(
- funnels_query,
- team,
- funnel_step,
- funnel_step_breakdown,
- funnel_trends_drop_off,
- funnel_trends_entrance_period_start,
- offset,
- include_recordings,
+def strict_funnel_query(date_from: str, date_to: str) -> FunnelsQuery:
+ return FunnelsQuery(
+ series=[
+ EventsNode(event="step one", name="step one"),
+ EventsNode(event="step two", name="step two"),
+ EventsNode(event="step three", name="step three"),
+ ],
+ interval=IntervalType.DAY,
+ dateRange=DateRange(date_from=date_from, date_to=date_to),
+ funnelsFilter=FunnelsFilter(funnelOrderType=StepOrderValue.STRICT),
)
@@ -73,82 +59,37 @@ class TestFunnelStrictStepsPersons(ClickhouseTestMixin, APIBaseTest):
def test_first_step(self):
self._create_sample_data_multiple_dropoffs()
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "strict",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- results = get_actors_legacy_filters(filters, self.team, funnel_step=1)
+ results = get_actors(
+ strict_funnel_query("2021-05-01 00:00:00", "2021-05-07 00:00:00"), self.team, funnel_step=1
+ )
self.assertEqual(35, len(results))
def test_second_step(self):
self._create_sample_data_multiple_dropoffs()
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "strict",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- results = get_actors_legacy_filters(filters, self.team, funnel_step=2)
+ results = get_actors(
+ strict_funnel_query("2021-05-01 00:00:00", "2021-05-07 00:00:00"), self.team, funnel_step=2
+ )
self.assertEqual(10, len(results))
def test_second_step_dropoff(self):
self._create_sample_data_multiple_dropoffs()
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "strict",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- results = get_actors_legacy_filters(filters, self.team, funnel_step=-2)
+ results = get_actors(
+ strict_funnel_query("2021-05-01 00:00:00", "2021-05-07 00:00:00"), self.team, funnel_step=-2
+ )
self.assertEqual(25, len(results))
def test_third_step(self):
self._create_sample_data_multiple_dropoffs()
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "strict",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "funnel_step": 3,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
- results = get_actors_legacy_filters(filters, self.team, funnel_step=3)
+ results = get_actors(
+ strict_funnel_query("2021-05-01 00:00:00", "2021-05-07 00:00:00"), self.team, funnel_step=3
+ )
self.assertEqual(0, len(results))
@@ -199,21 +140,9 @@ class TestFunnelStrictStepsPersons(ClickhouseTestMixin, APIBaseTest):
)
# First event, but no recording
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "strict",
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- results = get_actors_legacy_filters(filters, self.team, funnel_step=1, include_recordings=True)
+ results = get_actors(
+ strict_funnel_query("2021-01-01", "2021-01-08"), self.team, funnel_step=1, include_recordings=True
+ )
# self.assertEqual(results[0]["id"], p1.uuid)
self.assertEqual(results[0][0], p1.uuid)
@@ -224,21 +153,9 @@ class TestFunnelStrictStepsPersons(ClickhouseTestMixin, APIBaseTest):
)
# Second event, with recording
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "strict",
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- results = get_actors_legacy_filters(filters, self.team, funnel_step=2, include_recordings=True)
+ results = get_actors(
+ strict_funnel_query("2021-01-01", "2021-01-08"), self.team, funnel_step=2, include_recordings=True
+ )
# self.assertEqual(results[0]["id"], p1.uuid)
self.assertEqual(results[0][0], p1.uuid)
@@ -260,21 +177,9 @@ class TestFunnelStrictStepsPersons(ClickhouseTestMixin, APIBaseTest):
)
# Third event dropoff, with recording
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "strict",
- "date_from": "2021-01-01",
- "date_to": "2021-01-08",
- "interval": "day",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- results = get_actors_legacy_filters(filters, self.team, funnel_step=-3, include_recordings=True)
+ results = get_actors(
+ strict_funnel_query("2021-01-01", "2021-01-08"), self.team, funnel_step=-3, include_recordings=True
+ )
# self.assertEqual(results[0]["id"], p1.uuid)
self.assertEqual(results[0][0], p1.uuid)
diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_unordered_persons.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_unordered_persons.py
index c5e3b1bb2d24..da54535c5ec7 100644
--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_unordered_persons.py
+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel_unordered_persons.py
@@ -1,13 +1,9 @@
from datetime import datetime
-from typing import Any, Optional, cast
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
-from posthog.schema import FunnelsQuery
+from posthog.schema import DateRange, EventsNode, FunnelsFilter, FunnelsQuery, IntervalType, StepOrderValue
-from posthog.constants import INSIGHT_FUNNELS
-from posthog.hogql_queries.legacy_compatibility.filter_to_query import filter_to_query
-from posthog.models import Team
from posthog.test.test_journeys import journeys_for
from products.product_analytics.backend.hogql_queries.funnels.test.test_funnel_persons import get_actors
@@ -15,26 +11,16 @@ from products.product_analytics.backend.hogql_queries.funnels.test.test_funnel_p
FORMAT_TIME = "%Y-%m-%d 00:00:00"
-def get_actors_legacy_filters(
- filters: dict[str, Any],
- team: Team,
- funnel_step: Optional[int] = None,
- funnel_step_breakdown: Optional[str | float | list[str | float]] = None,
- funnel_trends_drop_off: Optional[bool] = None,
- funnel_trends_entrance_period_start: Optional[str] = None,
- offset: Optional[int] = None,
- include_recordings: bool = False,
-) -> list[list]:
- funnels_query = cast(FunnelsQuery, filter_to_query(filters))
- return get_actors(
- funnels_query,
- team,
- funnel_step,
- funnel_step_breakdown,
- funnel_trends_drop_off,
- funnel_trends_entrance_period_start,
- offset,
- include_recordings,
+def unordered_funnel_query() -> FunnelsQuery:
+ return FunnelsQuery(
+ series=[
+ EventsNode(event="step one", name="step one"),
+ EventsNode(event="step two", name="step two"),
+ EventsNode(event="step three", name="step three"),
+ ],
+ interval=IntervalType.DAY,
+ dateRange=DateRange(date_from="2021-05-01 00:00:00", date_to="2021-05-07 00:00:00"),
+ funnelsFilter=FunnelsFilter(funnelOrderType=StepOrderValue.UNORDERED),
)
@@ -60,105 +46,41 @@ class TestFunnelUnorderedStepsPersons(ClickhouseTestMixin, APIBaseTest):
journeys_for(events_by_person, self.team)
def test_invalid_steps(self):
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "unordered",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
+ query = unordered_funnel_query()
with self.assertRaisesMessage(ValueError, "Input should be a valid integer"):
- get_actors_legacy_filters(filters, self.team, funnel_step="blah") # type: ignore
+ get_actors(query, self.team, funnel_step="blah") # type: ignore
with self.assertRaisesMessage(ValueError, "Funnel steps are 1-indexed, so step 0 doesn't exist"):
- get_actors_legacy_filters(filters, self.team, funnel_step=0)
+ get_actors(query, self.team, funnel_step=0)
with self.assertRaisesMessage(ValueError, "The first valid drop-off argument for funnelStep is -2"):
- get_actors_legacy_filters(filters, self.team, funnel_step=-1)
+ get_actors(query, self.team, funnel_step=-1)
def test_first_step(self):
self._create_sample_data_multiple_dropoffs()
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "unordered",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- results = get_actors_legacy_filters(filters, self.team, funnel_step=1)
+
+ results = get_actors(unordered_funnel_query(), self.team, funnel_step=1)
self.assertEqual(35, len(results))
def test_last_step(self):
self._create_sample_data_multiple_dropoffs()
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "unordered",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- results = get_actors_legacy_filters(filters, self.team, funnel_step=3)
+
+ results = get_actors(unordered_funnel_query(), self.team, funnel_step=3)
self.assertEqual(5, len(results))
def test_second_step_dropoff(self):
self._create_sample_data_multiple_dropoffs()
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "unordered",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- results = get_actors_legacy_filters(filters, self.team, funnel_step=-2)
+
+ results = get_actors(unordered_funnel_query(), self.team, funnel_step=-2)
self.assertEqual(20, len(results))
def test_last_step_dropoff(self):
self._create_sample_data_multiple_dropoffs()
- filters = {
- "insight": INSIGHT_FUNNELS,
- "funnel_order_type": "unordered",
- "interval": "day",
- "date_from": "2021-05-01 00:00:00",
- "date_to": "2021-05-07 00:00:00",
- "funnel_window_days": 7,
- "events": [
- {"id": "step one", "order": 0},
- {"id": "step two", "order": 1},
- {"id": "step three", "order": 2},
- ],
- }
-
- results = get_actors_legacy_filters(filters, self.team, funnel_step=-3)
+
+ results = get_actors(unordered_funnel_query(), self.team, funnel_step=-3)
self.assertEqual(10, len(results))