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.

fix(replay): default missing entity type in RecordingsQuery filters (#89162)

posthog[bot]5329bfe7cd94
diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.py
index 9f72619c4738..2d16d63d48e0 100644
--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py
@@ -4,6 +4,7 @@ from typing import Any, Optional, cast
import posthoganalytics
from prometheus_client import Counter
+from rest_framework.exceptions import ValidationError
from posthog.schema import (
ActionsNode,
@@ -22,6 +23,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.ph_client import feature_enabled_or_false
@@ -40,6 +42,10 @@ from posthog.session_recordings.queries.utils import (
)
from posthog.types import AnyPropertyFilter
+ENTITY_TYPES_ACCEPTED_BY_LEGACY_ENTITY = frozenset(
+ {TREND_FILTER_TYPE_ACTIONS, TREND_FILTER_TYPE_DATA_WAREHOUSE, TREND_FILTER_TYPE_EVENTS}
+)
+
# Cap on the negative blocklist subquery, kept for memory safety. Sessions past the cap
# are silently not excluded, so hitting it is observed by check_negative_blocklist_truncation.
NEGATIVE_BLOCKLIST_LIMIT = 1_000_000
@@ -140,7 +146,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
continue
# this is always _positive_ operations
- entity_exprs = [_entity_to_expr(entity=entity)]
+ entity_exprs = [_entity_to_expr(entity=entity, team=team)]
if entity.properties:
entity_exprs.append(property_to_expr(entity.properties, team=team, scope="replay_entity"))
@@ -792,21 +798,38 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
def _is_negated_entity(raw_entity: dict[str, Any]) -> bool:
return bool(raw_entity.get("negation"))
+ @staticmethod
+ def _entity_node(
+ raw_entity: dict[str, Any], default_type: str
+ ) -> EventsNode | ActionsNode | DataWarehouseNode | str:
+ # 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 = (
+ raw_entity
+ if raw_entity.get("type") in ENTITY_TYPES_ACCEPTED_BY_LEGACY_ENTITY
+ else {**raw_entity, "type": default_type}
+ )
+ try:
+ return legacy_entity_to_node(Entity(entity), True, MathAvailability.Unavailable)
+ 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
+ # caller input, so report it as a bad request. DRF's ValidationError is not a
+ # ValueError, so a field that already validates itself still reports its own message.
+ raise ValidationError(f"Invalid {entity['type']} filter for id {raw_entity.get('id')!r}") from e
+
@property
def action_entities(self):
- # TODO what do we send to the API instead to avoid needing to do this
return [
- legacy_entity_to_node(Entity(e), True, MathAvailability.Unavailable)
+ self._entity_node(e, TREND_FILTER_TYPE_ACTIONS)
for e in self._query.actions or []
if not self._is_negated_entity(e)
]
@property
def event_entities(self):
- # TODO what do we send to the API instead to avoid needing to do this
- # TODO is this overkill since it feels like we only need a few things off the entity
return [
- legacy_entity_to_node(Entity(e), True, MathAvailability.Unavailable)
+ self._entity_node(e, TREND_FILTER_TYPE_EVENTS)
for e in self._query.events or []
if not self._is_negated_entity(e)
]
@@ -819,8 +842,12 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
def negated_entities(self) -> list[EventsNode | ActionsNode | DataWarehouseNode | str]:
# the legacy Entity class drops unknown keys, so negation is read off the raw dicts
return [
- legacy_entity_to_node(Entity(e), True, MathAvailability.Unavailable)
- for e in (self._query.actions or []) + (self._query.events or [])
+ self._entity_node(e, TREND_FILTER_TYPE_ACTIONS)
+ for e in self._query.actions or []
+ if self._is_negated_entity(e)
+ ] + [
+ self._entity_node(e, TREND_FILTER_TYPE_EVENTS)
+ for e in self._query.events or []
if self._is_negated_entity(e)
]
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 685f66ec8ca4..6796536514c9 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
@@ -2,7 +2,7 @@ import re
from contextlib import nullcontext
from datetime import UTC, datetime
from itertools import product
-from typing import Literal
+from typing import Any, Literal
from uuid import uuid4
from freezegun import freeze_time
@@ -24,9 +24,10 @@ from django.utils.timezone import now
from dateutil.relativedelta import relativedelta
from parameterized import parameterized, parameterized_class
+from rest_framework.exceptions import ValidationError
from tenacity import retry, stop_after_attempt, wait_exponential
-from posthog.schema import PersonsOnEventsMode, RecordingsQuery
+from posthog.schema import ActionsNode, EventsNode, PersonsOnEventsMode, RecordingsQuery
from posthog.hogql.ast import SelectQuery
from posthog.hogql.context import HogQLContext
@@ -835,6 +836,84 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
[],
)
+ @parameterized.expand(
+ [
+ ("events without a type", "events", None, EventsNode, "event_entities"),
+ ("actions without a type", "actions", None, ActionsNode, "action_entities"),
+ ("events with an unaccepted type", "events", "event", EventsNode, "event_entities"),
+ ("actions with an unaccepted type", "actions", "action", ActionsNode, "action_entities"),
+ ]
+ )
+ def test_entity_dicts_fall_back_to_their_source_list_type(
+ self,
+ _name: str,
+ source_list: str,
+ raw_type: str | None,
+ expected_node: type,
+ 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"
+ )
+ raw_entity: dict[str, Any] = {"id": entity_id}
+ if raw_type is not None:
+ raw_entity["type"] = raw_type
+
+ positive = ReplayFiltersEventsSubQuery(team=self.team, query=RecordingsQuery(**{source_list: [raw_entity]}))
+ assert isinstance(getattr(positive, entities_property)[0], expected_node)
+
+ negated = ReplayFiltersEventsSubQuery(
+ team=self.team, query=RecordingsQuery(**{source_list: [{**raw_entity, "negation": True}]})
+ )
+ assert isinstance(negated.negated_entities[0], expected_node)
+
+ @parameterized.expand(
+ [
+ ("an action in another project", True),
+ ("an action id that does not exist", False),
+ ]
+ )
+ def test_action_filter_outside_the_project_is_rejected(self, _name: str, action_exists: bool) -> None:
+ # The lookup used to be unscoped, so a foreign action's steps compiled into the caller's
+ # 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
+ else:
+ action_id = 0
+
+ sub_query = ReplayFiltersEventsSubQuery(
+ team=self.team, query=RecordingsQuery(actions=[{"id": action_id, "type": "actions"}])
+ )
+ with self.assertRaises(ValidationError):
+ sub_query.get_query_for_event_id_matching()
+
+ @parameterized.expand(
+ [
+ ("an event name in the actions list", "actions", "$pageview"),
+ ("a number in the events list", "events", 7),
+ ("no id at all", "actions", None),
+ ]
+ )
+ def test_entity_dict_the_node_cannot_hold_is_rejected(self, _name: str, source_list: str, entity_id: Any) -> None:
+ # ActionsNode.id is an int and EventsNode.event is a str, so the wrong id type used to
+ # raise a pydantic ValidationError here and escape as a 500.
+ sub_query = ReplayFiltersEventsSubQuery(
+ team=self.team, query=RecordingsQuery(**{source_list: [{"id": entity_id}]})
+ )
+ with self.assertRaises(ValidationError):
+ sub_query.get_query_for_event_id_matching()
+
+ 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")
+
+ sub_query = ReplayFiltersEventsSubQuery(
+ team=self.team, query=RecordingsQuery(actions=[{"id": action.id, "type": "actions"}])
+ )
+ assert sub_query.get_query_for_event_id_matching() is not None
+
@parameterized.expand([("AND",), ("OR",)])
def test_negated_event_filter_excludes_sessions_containing_event(self, operand: str) -> None:
user = "test_negated_event_filter-user"
diff --git a/posthog/session_recordings/queries/utils.py b/posthog/session_recordings/queries/utils.py
index ac3c7d196957..9daef51a17bd 100644
--- a/posthog/session_recordings/queries/utils.py
+++ b/posthog/session_recordings/queries/utils.py
@@ -3,6 +3,7 @@ from typing import NamedTuple
import structlog
import posthoganalytics
+from rest_framework.exceptions import ValidationError
from posthog.schema import (
ActionsNode,
@@ -167,10 +168,14 @@ 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 _entity_to_expr(entity: EventsNode | ActionsNode) -> ast.Expr:
+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":
- action = Action.objects.get(pk=entity.id)
+ # 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:
+ raise ValidationError(f"Action ID {entity.id} does not exist!")
return action_to_expr(action)
else:
if entity.event is None: