: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(heatmaps): filter a heatmap by events in the session (#91435)
jake sciotto9970c7b8a0f3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1b09152c156f..71d43c8eeee2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6776,6 +6776,10 @@ snapshots:hash: v1.k794b7964.ecb6fd1c2de83c13a08fad883f74a3b9e18e7381ea6803e2f6b66c98bc8c4d7c.SvgSm1w31kAgXE50mM9O_l6kdJVJ53oBmp1ukGpQPgoscenes-app-heatmap--iframe-example--light:hash: v1.k794b7964.d53f7271d90ce8ee4c2c3655b96f0bb148c6083e7bf9a76bb1ffd8bf5a36efce.EV3kCDfyPP58BHnE-ZQ9rbsF6CPMkDUvGaMvtLkhrtE+ scenes-app-heatmap--iframe-example-with-event-filter--dark:+ hash: v1.k794b7964.bbd85acb6734a7e1afe7b247ae8048aec3d781a8667f9e5d41dfc997804e7f71.BnvFMqUnpXoMSYfzTw4vHmxnryvU9fPhnwzB3JmFYS8+ scenes-app-heatmap--iframe-example-with-event-filter--light:+ hash: v1.k794b7964.3d105e9ca59cb010b11fb86dcb7987b8d13f0e1eb59054dedf266bb7b0c39fa0.SFsxSuBYo_ULVUw8MuU3dFAV-86JRLp4iSr7TTPKNT4scenes-app-heatmap--new--dark:hash: v1.k794b7964.cfd075c10189496c867372e36391cf5985948fe5a8137c434545f5825b15ac7e.IUvQTi7vHNPSGeWj-q6upJsHMLU3UpumxHwGBndOhYEscenes-app-heatmap--new--light:diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.test.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.test.tsindex 568d46944a0f..998833679ce5 100644--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.test.ts+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.test.ts@@ -1,5 +1,5 @@-import { heatmapApiPath, isWithinBounds } from 'lib/components/heatmaps/heatmapDataLogic'-import { HeatmapBoundsFilter } from 'lib/components/heatmaps/types'+import { eventFilterParam, heatmapApiPath, isWithinBounds } from 'lib/components/heatmaps/heatmapDataLogic'+import { CommonFilters, HeatmapBoundsFilter } from 'lib/components/heatmaps/types'import { AppContext } from '~/types'@@ -57,3 +57,20 @@ describe('heatmapApiPath', () => {expect(heatmapApiPath(context, endpoint)).toBe(expected)})})++describe('eventFilterParam', () => {+ it.each([+ ['no events', undefined, undefined],+ ['an empty list', [], undefined],+ // ActionFilter adds the row before the user picks an event, and the API rejects a null id.+ ['only rows without a picked event', [{ id: null }, { id: null }], undefined],+ ['a mix of picked and unpicked rows', [{ id: null }, { id: 'purchase' }], '[{"id":"purchase"}]'],+ [+ 'the property filters a picked row carries',+ [{ id: 'purchase', properties: [{ type: 'event', key: 'plan', value: 'pro' }] }],+ '[{"id":"purchase","properties":[{"type":"event","key":"plan","value":"pro"}]}]',+ ],+ ] as const)('%s', (_name, events, expected) => {+ expect(eventFilterParam(events as CommonFilters['events'])).toBe(expected)+ })+})diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.tsindex 42053e9e6165..adddb3dbc5e6 100644--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts@@ -123,6 +123,13 @@ export function heatmapApiPath(context: HeatmapDataLogicProps['context'], endpoireturn `/api/heatmap/${endpoint}`}+// A row added but not yet pointed at an event carries a null id. It selects nothing, and the API rejects+// it, so leave those out of the request instead of failing the whole heatmap over a half-filled row.+export function eventFilterParam(events: CommonFilters['events']): string | undefined {+ const selected = events?.filter((event) => !!event.id)+ return selected?.length ? JSON.stringify(selected) : undefined+}+export type HrefMatchType = 'exact' | 'pattern'export function isWithinBounds(@@ -476,7 +483,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([actions.setIsReady(false)- const { date_from, date_to, filter_test_accounts, cohort_ids } = values.commonFilters+ const { date_from, date_to, filter_test_accounts, cohort_ids, events } = values.commonFiltersconst { type, aggregation } = values.heatmapFilters// toolbar fetch collapses queryparams but this URL has multiple with the same name@@ -492,6 +499,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([aggregation,filter_test_accounts,cohort_ids: cohort_ids && cohort_ids.length > 0 ? cohort_ids : undefined,+ events: eventFilterParam(events),limit: UNBOUNDED_HEATMAP_LIMIT,},'?'@@ -517,7 +525,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([await breakpoint(100)- const { date_from, date_to, filter_test_accounts, cohort_ids } = values.commonFilters+ const { date_from, date_to, filter_test_accounts, cohort_ids, events } = values.commonFiltersconst { type } = values.heatmapFiltersconst apiURL = `${heatmapApiPath(props.context, 'events/')}${encodeParams(@@ -531,6 +539,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([viewport_width_max: values.viewportRange.max,filter_test_accounts,cohort_ids: cohort_ids && cohort_ids.length > 0 ? cohort_ids : undefined,+ events: eventFilterParam(events),points: JSON.stringify(area.points),},'?'@@ -709,6 +718,9 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([}),listeners(({ actions, values, props }) => ({setCommonFilters: () => {+ // The open drill-down lists interactions for the filters it was opened with. Close it so it+ // can't show sessions the new filters exclude; the user reselects a hotspot on the new overlay.+ actions.clearSelectedArea()actions.loadHeatmap()},setHeatmapFilters: () => {@@ -740,7 +752,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([return}- const { date_from, date_to, filter_test_accounts, cohort_ids } = values.commonFilters+ const { date_from, date_to, filter_test_accounts, cohort_ids, events } = values.commonFiltersconst { type } = values.heatmapFiltersconst nextOffset = currentEvents.results.length@@ -755,6 +767,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([viewport_width_max: values.viewportRange.max,filter_test_accounts,cohort_ids: cohort_ids && cohort_ids.length > 0 ? cohort_ids : undefined,+ events: eventFilterParam(events),points: JSON.stringify(area.points),offset: nextOffset,},diff --git a/frontend/src/lib/components/heatmaps/types.ts b/frontend/src/lib/components/heatmaps/types.tsindex 8e51b41eda58..5ce8b4ce686f 100644--- a/frontend/src/lib/components/heatmaps/types.ts+++ b/frontend/src/lib/components/heatmaps/types.ts@@ -3,6 +3,18 @@ export type CommonFilters = {date_to?: string | nullfilter_test_accounts?: booleancohort_ids?: number[]+ // A subset of FilterType['events'], spelled out because ~/types imports this file. Each entry is an+ // event name plus optional property filters, matching what ActionFilter emits.+ events?: HeatmapEventFilter[]+}++export type HeatmapEventFilter = {+ // Null while a freshly added row is waiting for the user to pick an event.+ id: string | null+ name?: string+ type?: string+ order?: number+ properties?: Record<string, any>[]}export type HeatmapKind = 'click' | 'rageclick' | 'mousemove' | 'scrolldepth'diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 2aa1ec455a69..9c40d6c292f3 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -217,6 +217,7 @@ export const FEATURE_FLAGS = {GATEWAY_PERSONAL_API_KEY: 'gateway-personal-api-key', // owner: #team-platform-featuresHEATMAPS_COHORT_FILTER: 'heatmaps-cohort-filter', // owner: #team-web-analyticsHEATMAPS_CREATION_FLOW: 'heatmaps-creation-flow', // owner: #team-web-analytics, gates the guided heatmap creation wizard at /heatmaps/new+ HEATMAPS_EVENT_FILTER: 'heatmaps-event-filter', // owner: #team-web-analyticsHEATMAPS_RECORDING_CLICKMAP: 'heatmaps-recording-clickmap', // owner: #team-web-analyticsHEATMAPS_SCREENSHOT_PREWARM: 'heatmaps-screenshot-prewarm', // owner: #team-web-analytics, pre-renders the screenshot while entering a URL in the wizardIMPROVED_COOKIELESS_MODE: 'improved-cookieless-mode', // owner: #team-web-analyticsdiff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex 5a4097f3429c..748edc68cf93 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -29,8 +29,10 @@ from posthog.hogql.ast import Constantfrom posthog.hogql.base import Exprfrom posthog.hogql.constants import MAX_SELECT_HEATMAPS_LIMIT, LimitContextfrom posthog.hogql.context import HogQLContext+from posthog.hogql.errors import QueryErrorfrom posthog.hogql.filters import replace_filtersfrom posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.api.forbid_destroy_model import ForbidDestroyModel@@ -86,6 +88,24 @@ MAX_CAPTURE_IMAGE_PIXELS = 50_000_000MAX_CAPTURE_TOTAL_BYTES = 60 * 1024 * 1024HEATMAPS_COHORT_FILTER_FLAG = "heatmaps-cohort-filter"+HEATMAPS_EVENT_FILTER_FLAG = "heatmaps-event-filter"++# A heatmap interaction and the event that qualifies its session are separate rows, and a session can+# straddle a day boundary — the click lands inside the requested window while the purchase that selects+# it sits just outside. Session replay hit this and widened its events scan by a day at each end; do the+# same here, or sessions on the boundary drop out of the heatmap.+EVENT_FILTER_SESSION_BUFFER = timedelta(days=1)++# The property filters on a selected event reach property_to_expr, which parses the key of a "hogql"+# property as an arbitrary expression. Heatmap access is its own API scope and its own access-control+# resource, so accepting that type would let a caller who may only read heatmaps read any table the+# project's HogQL database exposes. Accept only the types the heatmap filter offers.+EVENT_FILTER_PROPERTY_TYPES = frozenset({"element", "event"})++# Each selected event adds one events-table session subquery, and every property filter on it adds another+# predicate inside that subquery, so cap both. Neither cap is reachable from the in-app filter bar.+MAX_EVENT_FILTERS = 10+MAX_PROPERTIES_PER_EVENT_FILTER = 20logger = structlog.get_logger(__name__)@@ -105,6 +125,28 @@ def _heatmaps_cohort_filter_enabled(user: User, team: Team) -> bool:)+def _heatmaps_event_filter_enabled(user: User, team: Team) -> bool:+ return heatmaps_flag_enabled(+ HEATMAPS_EVENT_FILTER_FLAG,+ str(getattr(user, "distinct_id", "") or ""),+ team_id=team.id,+ organization_id=str(team.organization_id),+ )+++def _requests_event_filter(request: request.Request) -> bool:+ """Whether the request asks for an event filter, read before the serializer runs."""+ raw = request.query_params.get("events")+ if not raw:+ return False+ try:+ return bool(loads(raw))+ except JSONDecodeError:+ # The serializer turns this into a 400 either way; treat it as asking rather than letting a+ # malformed value walk past the access check.+ return True++def _reject_oversized_capture_image(image_bytes: bytes) -> None:try:with Image.open(BytesIO(image_bytes)) as im:@@ -303,6 +345,19 @@ class HeatmapsRequestSerializer(serializers.Serializer):help_text="JSON array of cohort IDs (e.g. '[123, 456]') to restrict results to people in those cohorts. ""Feature-flagged; ignored when the cohort filter is not enabled for the caller.",)+ events = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text='JSON array of event filters (e.g. \'[{"id": "purchase", "properties": []}]\') to restrict '+ "results to sessions in which those events occurred. Each entry needs a string 'id' (the event name) and "+ "may carry a 'properties' array of property filters applied to that event, each of type 'event' or "+ "'element'. Several entries are combined with AND: the session must contain a matching event for "+ f"every entry. At most {MAX_EVENT_FILTERS} entries, each with at most "+ f"{MAX_PROPERTIES_PER_EVENT_FILTER} property filters. Requires project-wide heatmap access, since "+ "the filter reads the project's events rather than one saved heatmap. "+ "Feature-flagged; ignored when the event filter is not enabled for the caller.",+ )limit = serializers.IntegerField(required=False,default=500,@@ -344,6 +399,39 @@ class HeatmapsRequestSerializer(serializers.Serializer):raise serializers.ValidationError(f"Cohort(s) not found or deleted: {missing}")return cohort_ids+ def validate_events(self, value: str | None) -> list[dict[str, Any]]:+ if value is None or value == "":+ return []+ try:+ events = loads(value)+ except JSONDecodeError:+ raise serializers.ValidationError("events must be valid JSON")+ if not isinstance(events, list) or not all(isinstance(entity, dict) for entity in events):+ raise serializers.ValidationError("events must be a JSON array of event objects")+ if len(events) > MAX_EVENT_FILTERS:+ raise serializers.ValidationError(f"events cannot have more than {MAX_EVENT_FILTERS} entries")+ for entity in events:+ if not isinstance(entity.get("id"), str):+ raise serializers.ValidationError("each event must have a string 'id'")+ properties = entity.get("properties")+ # These reach property_to_expr when the query is built, where a wrong shape raises and+ # surfaces as a 500. Reject it here so the caller gets a 400 instead.+ if properties is not None and (+ not isinstance(properties, list) or not all(isinstance(prop, dict) for prop in properties)+ ):+ raise serializers.ValidationError("event 'properties' must be a JSON array of property objects")+ if properties is not None and len(properties) > MAX_PROPERTIES_PER_EVENT_FILTER:+ raise serializers.ValidationError(+ f"an event cannot have more than {MAX_PROPERTIES_PER_EVENT_FILTER} property filters"+ )+ for prop in properties or []:+ if prop.get("type") not in EVENT_FILTER_PROPERTY_TYPES:+ raise serializers.ValidationError(+ "event property filters must have a 'type' of "+ f"{' or '.join(sorted(EVENT_FILTER_PROPERTY_TYPES))}"+ )+ return events+def validate_date(self, value, label: Literal["date_from", "date_to"]) -> date:try:if isinstance(value, str):@@ -496,7 +584,10 @@ class HeatmapAggregateQueryScopingPermission(AccessControlPermission):has at least the required access level on — the same value the in-app heatmap overlay alwaysqueries with (see heatmapDataLogic.ts). `url_pattern` requests always require resource-levelaccess: the query matches the pattern against every row in the dataset, so an object grant for- one saved heatmap can't bound what a broad pattern is allowed to read.+ one saved heatmap can't bound what a broad pattern is allowed to read. An `events` filter needs+ resource-level access for the same reason, one table over: it selects sessions out of the project's+ whole events table, so the counts it returns describe what the granted URL's visitors did away+ from it."""def has_permission(self, request, view) -> bool:@@ -534,6 +625,12 @@ class HeatmapAggregateQueryScopingPermission(AccessControlPermission):self.message = f"You do not have {required_level} access to this resource."return False+ if _requests_event_filter(request):+ # The event subqueries read the project's events table, not the granted saved heatmap, so an+ # object grant can't bound what they disclose either.+ self.message = f"You do not have {required_level} access to this resource."+ return False+# Prewarm rows are speculative implementation details, not user-saved authorization anchors.# Their creators implicitly own them, so including them would turn prewarming into aggregate-data access.candidates = SavedHeatmap.objects.filter(team=team, deleted=False, is_prewarm=False)@@ -582,6 +679,10 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):cast(User, request.user), self.team):request_serializer.validated_data.pop("cohort_ids")+ if request_serializer.validated_data.get("events") and not _heatmaps_event_filter_enabled(+ cast(User, request.user), self.team+ ):+ request_serializer.validated_data.pop("events")placeholders = self._build_placeholders(request_serializer.validated_data)is_scrolldepth_query = placeholders.get("type", None) == Constant(value="scrolldepth")@@ -593,10 +694,13 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if hide_zero_coordinates and not is_scrolldepth_query:exprs.append(parse_expr("NOT (x = 0 AND y = 0)"))+ date_from: date = request_serializer.validated_data["date_from"]+ date_to: date | None = request_serializer.validated_data.get("date_to", None)if request_serializer.validated_data.get("filter_test_accounts") is True:- date_from: date = request_serializer.validated_data["date_from"]- date_to: date | None = request_serializer.validated_data.get("date_to", None)exprs.append(self._build_test_accounts_filter(date_from, date_to))+ exprs.extend(+ self._build_event_filters(date_from, date_to, request_serializer.validated_data.get("events") or [])+ )unbounded = limit == 0query_placeholders: dict[str, Expr] = {@@ -639,31 +743,89 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):aggregation_count = parse_expr(aggregation_value)return aggregation_count- def _build_test_accounts_filter(self, date_from: date, date_to: date | None) -> ast.CompareOperation:- # The heatmap predicate treats date_to as an inclusive day via `timestamp <= {date_to} + interval 1 day`.- # Pass the same bound as an explicit next-day-midnight datetime, which HogQLFilters uses verbatim with a- # strict `<`, so the events subquery covers the same inclusive days as the main heatmap query. A date-only- # value would instead snap to the end of that next day and widen the window by a day.- events_date_to = (date_to or date.today()) + timedelta(days=1)- events_select = replace_filters(- parse_select(- "SELECT distinct $session_id FROM events where notEmpty($session_id) AND {filters}", placeholders={}- ),- HogQLFilters(- filterTestAccounts=True,- dateRange=DateRange(- date_from=date_from.strftime("%Y-%m-%d"),- date_to=events_date_to.strftime("%Y-%m-%dT00:00:00"),+ def _sessions_seen_in_events(+ self,+ date_from: date,+ date_to: date,+ *,+ filter_test_accounts: bool = False,+ predicate: ast.Expr | None = None,+ ) -> ast.SelectQuery:+ """The session ids the events table saw in a window, as a subquery to match heatmap rows against."""+ events_select = cast(+ ast.SelectQuery,+ replace_filters(+ parse_select(+ "SELECT distinct $session_id FROM events where notEmpty($session_id) AND {filters}",+ placeholders={},),+ HogQLFilters(+ filterTestAccounts=filter_test_accounts,+ dateRange=DateRange(+ date_from=date_from.strftime("%Y-%m-%d"),+ date_to=date_to.strftime("%Y-%m-%dT00:00:00"),+ ),+ ),+ self.team,),- self.team,)+ if predicate is not None:+ events_select.where = ast.And(exprs=[events_select.where, predicate]) if events_select.where else predicate+ return events_select++ @staticmethod+ def _session_id_in(events_select: ast.SelectQuery) -> ast.CompareOperation:+ # Stays a plain IN: the resolver rewrites an IN whose subquery reads events into a GLOBAL IN, so the+ # set is built once on the initiator instead of on every heatmaps shard.return ast.CompareOperation(op=ast.CompareOperationOp.In,left=ast.Field(chain=["session_id"]),right=events_select,)+ def _build_test_accounts_filter(self, date_from: date, date_to: date | None) -> ast.CompareOperation:+ # The heatmap predicate treats date_to as an inclusive day via `timestamp <= {date_to} + interval 1 day`.+ # Pass the same bound as an explicit next-day-midnight datetime, which HogQLFilters uses verbatim with a+ # strict `<`, so the events subquery covers the same inclusive days as the main heatmap query. A date-only+ # value would instead snap to the end of that next day and widen the window by a day.+ events_date_to = (date_to or date.today()) + timedelta(days=1)+ return self._session_id_in(self._sessions_seen_in_events(date_from, events_date_to, filter_test_accounts=True))++ def _build_event_filters(+ self,+ date_from: date,+ date_to: date | None,+ events: List[dict[str, Any]], # noqa: UP006+ ) -> List[ast.Expr]: # noqa: UP006+ """One session subquery per selected event, so a heatmap row survives only when its session+ contains a matching event for every entry.++ Session replay compiled several event filters into one events query and moved back to one query+ per filter, because the combined form kept producing bugs. The cost here is an extra subquery+ per filter, and a heatmap carries a handful of filters at most.+ """+ events_date_from = date_from - EVENT_FILTER_SESSION_BUFFER+ events_date_to = (date_to or date.today()) + timedelta(days=1) + EVENT_FILTER_SESSION_BUFFER++ filters: list[ast.Expr] = []+ for entity in events:+ predicate: ast.Expr = parse_expr("event = {event}", {"event": Constant(value=entity["id"])})+ entity_properties = entity.get("properties")+ if entity_properties:+ # strict, so a property the caller got wrong is a 400 rather than a filter that quietly+ # drops itself and returns the unfiltered heatmap.+ try:+ properties_expr = property_to_expr(entity_properties, self.team, scope="event", strict=True)+ except (QueryError, NotImplementedError, TypeError, ValueError) as error:+ raise serializers.ValidationError(f"Invalid property filter on event '{entity['id']}': {error}")+ predicate = ast.And(exprs=[predicate, properties_expr])+ filters.append(+ self._session_id_in(+ self._sessions_seen_in_events(events_date_from, events_date_to, predicate=predicate)+ )+ )+ return filters+@staticmethoddef _build_placeholders(validated_data: dict[str, Any]) -> dict[str, Expr]:placeholders: dict[str, Expr] = {}@@ -672,6 +834,9 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if value:placeholders[key] = ast.Array(exprs=[Constant(value=cid) for cid in value])continue+ if key == "events":+ # Compiled into session subqueries by _build_event_filters, not a heatmaps-table predicate.+ continueplaceholders[key] = Constant(value=value)placeholders.setdefault("date_to", Constant(value=date.today().strftime("%Y-%m-%d")))return placeholders@@ -778,6 +943,8 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):cast(User, request.user), self.team):validated_data.pop("cohort_ids")+ if validated_data.get("events") and not _heatmaps_event_filter_enabled(cast(User, request.user), self.team):+ validated_data.pop("events")placeholders = self._build_placeholders(validated_data)@@ -805,10 +972,11 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):else:exprs.append(ast.Or(exprs=point_conditions))+ date_from: date = validated_data["date_from"]+ date_to: date | None = validated_data.get("date_to", None)if validated_data.get("filter_test_accounts") is True:- date_from: date = validated_data["date_from"]- date_to: date | None = validated_data.get("date_to", None)exprs.append(self._build_test_accounts_filter(date_from, date_to))+ exprs.extend(self._build_event_filters(date_from, date_to, validated_data.get("events") or []))# First get total countcount_stmt = parse_select(diff --git a/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr b/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambrindex 61bdc0a1102a..4ea633a7ce19 100644--- a/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr+++ b/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr@@ -1780,3 +1780,307 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordings.test_event_filter_also_narrows_the_interaction_drill_down+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT count() AS `count()`+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), and(ifNull(equals(round(divide(heatmaps.x, heatmaps.viewport_width), 2), 0.0), 0), equals(multiply(heatmaps.y, heatmaps.scale_factor), 16), equals(heatmaps.pointer_target_fixed, 1)), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'purchase')))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_event_filter_also_narrows_the_interaction_drill_down.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT heatmaps.session_id AS session_id,+ heatmaps.distinct_id AS distinct_id,+ toTimeZone(heatmaps.timestamp, 'UTC') AS timestamp,+ round(divide(heatmaps.x, heatmaps.viewport_width), 2) AS pointer_relative_x,+ multiply(heatmaps.y, heatmaps.scale_factor) AS pointer_y,+ heatmaps.current_url AS current_url,+ heatmaps.type AS type+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), and(ifNull(equals(round(divide(heatmaps.x, heatmaps.viewport_width), 2), 0.0), 0), equals(multiply(heatmaps.y, heatmaps.scale_factor), 16), equals(heatmaps.pointer_target_fixed, 1)), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'purchase')))))+ ORDER BY toTimeZone(heatmaps.timestamp, 'UTC') DESC+ LIMIT 50+ OFFSET 0 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_event_filter_applies_the_property_filters_carried_by_an_event+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT pointer_target_fixed AS pointer_target_fixed,+ pointer_relative_x AS pointer_relative_x,+ client_y AS client_y,+ count(*) AS cnt+ FROM+ (SELECT heatmaps.distinct_id AS distinct_id,+ heatmaps.pointer_target_fixed AS pointer_target_fixed,+ round(divide(heatmaps.x, heatmaps.viewport_width), 2) AS pointer_relative_x,+ multiply(heatmaps.y, heatmaps.scale_factor) AS client_y+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), and(equals(events.event, 'purchase'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'pro'), 0)))))))+ GROUP BY pointer_target_fixed,+ pointer_relative_x,+ client_y+ ORDER BY cnt DESC+ LIMIT 501+ OFFSET 0 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_event_filter_applies_the_property_filters_carried_by_an_event.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), and(equals(events.event, 'purchase'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'plan'), ''), 'null'), '^"|"$', ''), 'pro'), 0))))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_event_filter_keeps_a_session_whose_event_landed_before_the_window+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT pointer_target_fixed AS pointer_target_fixed,+ pointer_relative_x AS pointer_relative_x,+ client_y AS client_y,+ count(*) AS cnt+ FROM+ (SELECT heatmaps.distinct_id AS distinct_id,+ heatmaps.pointer_target_fixed AS pointer_target_fixed,+ round(divide(heatmaps.x, heatmaps.viewport_width), 2) AS pointer_relative_x,+ multiply(heatmaps.y, heatmaps.scale_factor) AS client_y+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'purchase'))))))+ GROUP BY pointer_target_fixed,+ pointer_relative_x,+ client_y+ ORDER BY cnt DESC+ LIMIT 501+ OFFSET 0 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_event_filter_keeps_a_session_whose_event_landed_before_the_window.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'purchase')))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_event_filter_narrows_to_sessions_containing_every_selected_event+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT pointer_target_fixed AS pointer_target_fixed,+ pointer_relative_x AS pointer_relative_x,+ client_y AS client_y,+ count(*) AS cnt+ FROM+ (SELECT heatmaps.distinct_id AS distinct_id,+ heatmaps.pointer_target_fixed AS pointer_target_fixed,+ round(divide(heatmaps.x, heatmaps.viewport_width), 2) AS pointer_relative_x,+ multiply(heatmaps.y, heatmaps.scale_factor) AS client_y+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'purchase'))))))+ GROUP BY pointer_target_fixed,+ pointer_relative_x,+ client_y+ ORDER BY cnt DESC+ LIMIT 501+ OFFSET 0 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_event_filter_narrows_to_sessions_containing_every_selected_event.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'purchase')))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_event_filter_narrows_to_sessions_containing_every_selected_event.2+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT pointer_target_fixed AS pointer_target_fixed,+ pointer_relative_x AS pointer_relative_x,+ client_y AS client_y,+ count(*) AS cnt+ FROM+ (SELECT heatmaps.distinct_id AS distinct_id,+ heatmaps.pointer_target_fixed AS pointer_target_fixed,+ round(divide(heatmaps.x, heatmaps.viewport_width), 2) AS pointer_relative_x,+ multiply(heatmaps.y, heatmaps.scale_factor) AS client_y+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'purchase')))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'signed_up'))))))+ GROUP BY pointer_target_fixed,+ pointer_relative_x,+ client_y+ ORDER BY cnt DESC+ LIMIT 501+ OFFSET 0 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestSessionRecordings.test_event_filter_narrows_to_sessions_containing_every_selected_event.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(not(heatmaps.pointer_target_fixed)) AS total,+ countIf(and(greater(heatmaps.y, heatmaps.viewport_height), not(heatmaps.pointer_target_fixed))) AS below_fold,+ round(quantile(0.5)(multiply(heatmaps.viewport_height, heatmaps.scale_factor))) AS median_viewport_height+ FROM heatmaps+ WHERE and(equals(heatmaps.team_id, 99999), equals(heatmaps.type, 'click'), ifNull(greaterOrEquals(heatmaps.timestamp, toDateTime64(toDate('2023-03-08'), 6, 'UTC')), 0), lessOrEquals(heatmaps.timestamp, plus('2025-03-31', toIntervalDay(1))), not(and(equals(heatmaps.x, 0), equals(heatmaps.y, 0))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'purchase')))), globalIn(heatmaps.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ WHERE and(equals(events.team_id, 99999), and(notEmpty(events.`$session_id`), and(less(events.timestamp, toDateTime64('2025-04-02 00:00:00.000000', 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('2023-03-07 00:00:00.000000', 6, 'UTC')))), equals(events.event, 'signed_up')))))+ LIMIT 1000000 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---diff --git a/products/web_analytics/backend/test/test_heatmap_access_control.py b/products/web_analytics/backend/test/test_heatmap_access_control.pyindex 54bb3261e0c5..658eb6697439 100644--- a/products/web_analytics/backend/test/test_heatmap_access_control.py+++ b/products/web_analytics/backend/test/test_heatmap_access_control.py@@ -391,13 +391,15 @@ class TestHeatmapAggregateQueryAccessControl(ClickhouseTestMixin, APIBaseTest):},)- def _query_aggregate(self, url_exact: str | None = None, url_pattern: str | None = None):+ def _query_aggregate(self, url_exact: str | None = None, url_pattern: str | None = None, events: str | None = None):self.client.force_login(self.viewer_user)params: dict[str, str] = {"type": "click", "date_from": "2023-03-01"}if url_exact is not None:params["url_exact"] = url_exactif url_pattern is not None:params["url_pattern"] = url_pattern+ if events is not None:+ params["events"] = eventsreturn self.client.get(f"/api/environments/{self.team.pk}/heatmaps/", params)def test_object_grant_does_not_expose_aggregate_data_for_other_urls(self):@@ -449,6 +451,29 @@ class TestHeatmapAggregateQueryAccessControl(ClickhouseTestMixin, APIBaseTest):response = self._query_aggregate(url_pattern=url_pattern)self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())+ @parameterized.expand(+ [+ ("bare_event", '[{"id": "purchase"}]'),+ (+ "event_with_properties",+ '[{"id": "purchase", "properties": [{"type": "event", "key": "plan", "value": "pro"}]}]',+ ),+ # A malformed value counts as asking, or the check could be sidestepped by sending nonsense.+ ("malformed_events", "not-json"),+ ]+ )+ def test_object_grant_never_authorizes_an_event_filter(self, _name, events):+ # An event filter selects sessions out of the project's whole events table, so the counts it+ # returns describe what the granted URL's visitors did away from it. An object grant on one+ # SavedHeatmap can't bound that, so an event filter needs resource-level access, as url_pattern does.+ response = self._query_aggregate(url_exact="https://example.com/authorized", events=events)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())++ def test_object_grant_still_allows_a_query_carrying_an_empty_event_filter(self):+ # An empty list reads no events at all, so it must not cost the user the URL they were granted.+ response = self._query_aggregate(url_exact="https://example.com/authorized", events="[]")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+def test_object_grant_cannot_smuggle_unauthorized_url_via_conflicting_pattern(self):# Regression: when url_exact and url_pattern differ, HeatmapsRequestSerializer.validate()# drops url_exact and the query runs against url_pattern. The permission check must resolvediff --git a/products/web_analytics/backend/test/test_heatmaps_api.py b/products/web_analytics/backend/test/test_heatmaps_api.pyindex 963e092b6ab6..6dd824cad78f 100644--- a/products/web_analytics/backend/test/test_heatmaps_api.py+++ b/products/web_analytics/backend/test/test_heatmaps_api.py@@ -1,3 +1,8 @@+from collections.abc import Iterator+from contextlib import contextmanager+from json import dumps+from urllib.parse import quote+import freezegunfrom posthog.test.base import (APIBaseTest,@@ -6,6 +11,7 @@ from posthog.test.base import (_create_event,snapshot_clickhouse_queries,)+from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import status@@ -721,3 +727,148 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)self._create_heatmap_event("session_1", "scrolldepth", x=0, y=0)self._assert_heatmap_result_count({"date_from": "2023-03-08", "type": "scrolldepth"}, 1)++ @contextmanager+ def _event_filter_flag(self, enabled: bool) -> Iterator[None]:+ with patch(+ "products.web_analytics.backend.api.heatmaps_utils.posthoganalytics.feature_enabled",+ return_value=enabled,+ ):+ yield++ @staticmethod+ def _events_param(events: list[dict]) -> str:+ return quote(dumps(events), safe="")++ def _heatmap_x_positions(self, params: dict[str, str | int | None]) -> list[float]:+ response = self._get_heatmap(params)+ return sorted(result["pointer_relative_x"] for result in response.data["results"])++ def _create_three_sessions_at_distinct_positions(self) -> None:+ self._create_heatmap_event("session_1", "click", "2023-03-08T09:00:00", viewport_width=100, x=5, y=10)+ self._create_heatmap_event("session_2", "click", "2023-03-08T09:00:00", viewport_width=100, x=50, y=10)+ self._create_heatmap_event("session_3", "click", "2023-03-08T09:00:00", viewport_width=100, x=100, y=10)++ @freezegun.freeze_time("2025-03-31")+ @snapshot_clickhouse_queries+ def test_event_filter_narrows_to_sessions_containing_every_selected_event(self) -> None:+ self._create_three_sessions_at_distinct_positions()+ for session_id, event_names in [+ ("session_1", ["purchase", "signed_up"]),+ ("session_2", ["purchase"]),+ ("session_3", ["signed_up"]),+ ]:+ for event_name in event_names:+ self.create_event(+ session_id=session_id, timestamp="2023-03-08T09:00:00", event_name=event_name, properties={}+ )++ with self._event_filter_flag(True):+ one_event = self._events_param([{"id": "purchase"}])+ assert self._heatmap_x_positions({"date_from": "2023-03-08", "events": one_event}) == [0.0, 0.5]++ two_events = self._events_param([{"id": "purchase"}, {"id": "signed_up"}])+ assert self._heatmap_x_positions({"date_from": "2023-03-08", "events": two_events}) == [0.0]++ @freezegun.freeze_time("2025-03-31")+ @snapshot_clickhouse_queries+ def test_event_filter_applies_the_property_filters_carried_by_an_event(self) -> None:+ self._create_three_sessions_at_distinct_positions()+ self.create_event(+ session_id="session_1", timestamp="2023-03-08T09:00:00", event_name="purchase", properties={"plan": "pro"}+ )+ self.create_event(+ session_id="session_2", timestamp="2023-03-08T09:00:00", event_name="purchase", properties={"plan": "free"}+ )++ events = self._events_param(+ [+ {+ "id": "purchase",+ "properties": [{"key": "plan", "value": "pro", "operator": "exact", "type": "event"}],+ }+ ]+ )+ with self._event_filter_flag(True):+ assert self._heatmap_x_positions({"date_from": "2023-03-08", "events": events}) == [0.0]++ @freezegun.freeze_time("2025-03-31")+ @snapshot_clickhouse_queries+ def test_event_filter_keeps_a_session_whose_event_landed_before_the_window(self) -> None:+ # The interaction is inside the window and the event that selects it is not, because the session+ # crossed midnight. The events scan reaches a day past each end of the window so this still matches.+ self._create_heatmap_event("session_1", "click", "2023-03-08T00:30:00", viewport_width=100, x=5, y=10)+ self.create_event(session_id="session_1", timestamp="2023-03-07T23:50:00", event_name="purchase", properties={})++ events = self._events_param([{"id": "purchase"}])+ with self._event_filter_flag(True):+ assert self._heatmap_x_positions({"date_from": "2023-03-08", "events": events}) == [0.0]++ @freezegun.freeze_time("2025-03-31")+ def test_event_filter_is_ignored_when_the_flag_is_off(self) -> None:+ self._create_three_sessions_at_distinct_positions()+ self.create_event(session_id="session_1", timestamp="2023-03-08T09:00:00", event_name="purchase", properties={})++ events = self._events_param([{"id": "purchase"}])+ with self._event_filter_flag(False):+ assert self._heatmap_x_positions({"date_from": "2023-03-08", "events": events}) == [0.0, 0.5, 1.0]++ @freezegun.freeze_time("2025-03-31")+ @snapshot_clickhouse_queries+ def test_event_filter_also_narrows_the_interaction_drill_down(self) -> None:+ # The drill-down has to answer for the same sessions as the heatmap it was opened from, or a hotspot+ # lists interactions the heatmap already filtered out.+ self._create_heatmap_event("session_1", "click", "2023-03-08T09:00:00", viewport_width=100, x=5, y=10)+ self._create_heatmap_event("session_2", "click", "2023-03-08T09:00:00", viewport_width=100, x=5, y=10)+ self.create_event(session_id="session_1", timestamp="2023-03-08T09:00:00", event_name="purchase", properties={})++ points = quote(dumps([{"x": 0.0, "y": 16, "target_fixed": True}]), safe="")+ events = self._events_param([{"id": "purchase"}])+ with self._event_filter_flag(True):+ response = self.client.get(f"/api/heatmap/events/?date_from=2023-03-08&points={points}&events={events}")+ assert response.status_code == status.HTTP_200_OK, response.data+ assert [result["session_id"] for result in response.data["results"]] == ["session_1"]++ @parameterized.expand(+ [+ ("not_json", "purchase"),+ ("not_a_list", '{"id": "purchase"}'),+ ("entry_is_not_an_object", '["purchase"]'),+ ("missing_id", '[{"properties": []}]'),+ ("id_is_not_a_string", '[{"id": 1}]'),+ ("properties_is_not_a_list", '[{"id": "purchase", "properties": "plan"}]'),+ ("properties_entries_are_not_objects", '[{"id": "purchase", "properties": ["plan"]}]'),+ # A "hogql" property carries a raw expression the caller authored. Accepting it here would let+ # a heatmap-only caller read any table the HogQL database exposes, so the type is not allowed.+ ("hogql_property_type", '[{"id": "purchase", "properties": [{"type": "hogql", "key": "1"}]}]'),+ (+ "cohort_property_type",+ '[{"id": "purchase", "properties": [{"type": "cohort", "key": "id", "value": 1}]}]',+ ),+ (+ "person_property_type",+ '[{"id": "purchase", "properties": [{"type": "person", "key": "email", "value": "a"}]}]',+ ),+ # Each entry adds an events-table subquery, so the count is capped (11 entries here).+ ("too_many_events", dumps([{"id": f"e{i}"} for i in range(11)])),+ # Every property adds a predicate inside that subquery, so those are capped too (21 here).+ (+ "too_many_properties_on_one_event",+ dumps(+ [+ {+ "id": "purchase",+ "properties": [{"type": "event", "key": f"p{i}", "value": "x"} for i in range(21)],+ }+ ]+ ),+ ),+ ]+ )+ def test_event_filter_rejects_malformed_or_disallowed_events(self, _name: str, events: str) -> None:+ # A bad shape reaches property_to_expr while the query builds and surfaces as a 500, and a+ # disallowed property type widens what the caller can read. Both are turned away as a 400.+ self._assert_heatmap_no_result_count(+ {"date_from": "2023-03-08", "events": quote(events, safe="")},+ expected_status_code=status.HTTP_400_BAD_REQUEST,+ )diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex 538d8974a7be..3853d145509e 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -831,6 +831,11 @@ export type HeatmapsListParams = {* @minLength 1*/date_to?: string+ /**+ * JSON array of event filters (e.g. '[{"id": "purchase", "properties": []}]') to restrict results to sessions in which those events occurred. Each entry needs a string 'id' (the event name) and may carry a 'properties' array of property filters applied to that event, each of type 'event' or 'element'. Several entries are combined with AND: the session must contain a matching event for every entry. At most 10 entries, each with at most 20 property filters. Requires project-wide heatmap access, since the filter reads the project's events rather than one saved heatmap. Feature-flagged; ignored when the event filter is not enabled for the caller.+ * @nullable+ */+ events?: string | null/*** When true, exclude sessions from internal/test accounts using the project's test-account filters.* @nullable@@ -908,6 +913,11 @@ export type HeatmapsEventsRetrieveParams = {* @minLength 1*/date_to?: string+ /**+ * JSON array of event filters (e.g. '[{"id": "purchase", "properties": []}]') to restrict results to sessions in which those events occurred. Each entry needs a string 'id' (the event name) and may carry a 'properties' array of property filters applied to that event, each of type 'event' or 'element'. Several entries are combined with AND: the session must contain a matching event for every entry. At most 10 entries, each with at most 20 property filters. Requires project-wide heatmap access, since the filter reads the project's events rather than one saved heatmap. Feature-flagged; ignored when the event filter is not enabled for the caller.+ * @nullable+ */+ events?: string | null/*** When true, exclude sessions from internal/test accounts using the project's test-account filters.* @nullablediff --git a/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx b/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsxindex f7347168709a..2b604f519956 100644--- a/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx+++ b/products/web_analytics/frontend/heatmaps/components/FilterPanel.tsx@@ -1,13 +1,14 @@import { useActions, useValues } from 'kea'import { useEffect, useState } from 'react'-import { IconGear, IconLaptop, IconPhone, IconTabletLandscape, IconTabletPortrait } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'+import { IconFilter, IconGear, IconLaptop, IconPhone, IconTabletLandscape, IconTabletPortrait } from '@posthog/icons'+import { LemonBadge, LemonBanner, LemonButton, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'import { HeatmapsSettings } from 'lib/components/heatmaps/HeatMapsSettings'import { SectionSetting } from 'lib/components/heatmaps/HeatMapsSettings'+import { HeatmapEventFilter } from 'lib/components/heatmaps/types'import { heatmapDateOptions } from 'lib/components/IframedToolbarBrowser/utils'import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'@@ -16,6 +17,8 @@ import { LoadingBar } from 'lib/lemon-ui/LoadingBar'import { Popover } from 'lib/lemon-ui/Popover'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from 'scenes/feature-flags/cohortPickerProps'+import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'+import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter'import { AnyPropertyFilter, CohortPropertyFilter, HeatmapType, PropertyFilterType, PropertyOperator } from '~/types'@@ -130,6 +133,7 @@ export function FilterPanel({lockedWidth?: number}): JSX.Element {const [isSettingsOpen, setIsSettingsOpen] = useState(false)+ const [isEventFilterOpen, setIsEventFilterOpen] = useState(false)const {heatmapFilters,heatmapColorPalette,@@ -145,6 +149,8 @@ export function FilterPanel({)const cohortFilterEnabled = useFeatureFlag('HEATMAPS_COHORT_FILTER')+ const eventFilterEnabled = useFeatureFlag('HEATMAPS_EVENT_FILTER')+ const eventFilterCount = commonFilters?.events?.length ?? 0const debouncedLoading = useDebounceLoading(rawHeatmapLoading ?? false)@@ -188,6 +194,63 @@ export function FilterPanel({/></div>)}+ {eventFilterEnabled && (+ <div className="mt-2 md:mt-0">+ <Popover+ overlay={+ // The filter bar is a single row of controls, so the event list, which grows a+ // row per event, sits in a popover rather than stretching the row it lives in.+ <div className="p-2 w-96">+ <ActionFilter+ bordered+ filters={{ events: commonFilters?.events ?? [] }}+ setFilters={(filters) => {+ setCommonFilters?.({+ ...commonFilters,+ // ActionFilter types events as the loose Record shape; narrow+ // back to what heatmapDataLogic serializes.+ events: (filters.events ?? []) as HeatmapEventFilter[],+ })+ }}+ typeKey="heatmap-events"+ buttonCopy="Add event"+ mathAvailability={MathAvailability.None}+ actionsTaxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}+ // "All events" matches every session, so as a filter it does nothing.+ excludedProperties={{ [TaxonomicFilterGroupType.Events]: [null] }}+ propertiesTaxonomicGroupTypes={[+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.EventFeatureFlags,+ ]}+ propertyFiltersPopover+ hideRename+ hideDuplicate+ showNestedArrow={false}+ />+ </div>+ }+ visible={isEventFilterOpen}+ onClickOutside={() => setIsEventFilterOpen(false)}+ placement="bottom"+ >+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconFilter />}+ sideIcon={+ eventFilterCount ? (+ <LemonBadge.Number count={eventFilterCount} size="small" />+ ) : undefined+ }+ onClick={() => setIsEventFilterOpen(!isEventFilterOpen)}+ tooltip="Only show interactions from sessions where these events happened"+ data-attr="heatmap-event-filter"+ >+ Filter by event+ </LemonButton>+ </Popover>+ </div>+ )}<div className="mt-2 md:mt-0"><Popoveroverlay={diff --git a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsxindex 81ecf368b06e..05adc1d84c47 100644--- a/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx+++ b/products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx@@ -1,5 +1,6 @@import { Meta, StoryObj } from '@storybook/react'+import { FEATURE_FLAGS } from 'lib/constants'import { App } from 'scenes/App'import { urls } from 'scenes/urls'@@ -80,6 +81,11 @@ export const IframeExample: Story = {// Wait for heatmap canvas to be ready with data loadedwaitForSelector: '.heatmaps-ready',waitForLoadersToDisappear: true,+ // The overlay is 800px tall until the heatmap data arrives, then grows to fit the lowest+ // point. The app shell fixes its own height before the fetch resolves, so at the default+ // 720px viewport the page height depended on which of the two won the race. A viewport at+ // least as tall as the loaded overlay makes both states resolve to the same height.+ viewport: { width: 1280, height: 1300 },},},decorators: [@@ -110,6 +116,14 @@ export const IframeExample: Story = {],}+export const IframeExampleWithEventFilter: Story = {+ parameters: {+ ...IframeExample.parameters,+ featureFlags: [FEATURE_FLAGS.HEATMAPS_EVENT_FILTER],+ },+ decorators: IframeExample.decorators,+}+export const New: Story = {parameters: {pageUrl: urls.heatmap('new'),diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5197d608c611..d00b73ec4130 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -93562,6 +93562,11 @@ export namespace Schemas {* @minLength 1*/date_to?: string;+ /**+ * JSON array of event filters (e.g. '[{"id": "purchase", "properties": []}]') to restrict results to sessions in which those events occurred. Each entry needs a string 'id' (the event name) and may carry a 'properties' array of property filters applied to that event, each of type 'event' or 'element'. Several entries are combined with AND: the session must contain a matching event for every entry. At most 10 entries, each with at most 20 property filters. Requires project-wide heatmap access, since the filter reads the project's events rather than one saved heatmap. Feature-flagged; ignored when the event filter is not enabled for the caller.+ * @nullable+ */+ events?: string | null;/*** When true, exclude sessions from internal/test accounts using the project's test-account filters.* @nullable@@ -93640,6 +93645,11 @@ export namespace Schemas {* @minLength 1*/date_to?: string;+ /**+ * JSON array of event filters (e.g. '[{"id": "purchase", "properties": []}]') to restrict results to sessions in which those events occurred. Each entry needs a string 'id' (the event name) and may carry a 'properties' array of property filters applied to that event, each of type 'event' or 'element'. Several entries are combined with AND: the session must contain a matching event for every entry. At most 10 entries, each with at most 20 property filters. Requires project-wide heatmap access, since the filter reads the project's events rather than one saved heatmap. Feature-flagged; ignored when the event filter is not enabled for the caller.+ * @nullable+ */+ events?: string | null;/*** When true, exclude sessions from internal/test accounts using the project's test-account filters.* @nullablediff --git a/services/mcp/src/generated/web_analytics/api.ts b/services/mcp/src/generated/web_analytics/api.tsindex 48b5846e719a..c8887e08f695 100644--- a/services/mcp/src/generated/web_analytics/api.ts+++ b/services/mcp/src/generated/web_analytics/api.ts@@ -58,6 +58,12 @@ export const HeatmapsListQueryParams = /* @__PURE__ */ zod.object({.min(1).optional().describe("End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today."),+ events: zod+ .string()+ .nullish()+ .describe(+ "JSON array of event filters (e.g. '[{\"id\": \"purchase\", \"properties\": []}]') to restrict results to sessions in which those events occurred. Each entry needs a string 'id' (the event name) and may carry a 'properties' array of property filters applied to that event, each of type 'event' or 'element'. Several entries are combined with AND: the session must contain a matching event for every entry. At most 10 entries, each with at most 20 property filters. Requires project-wide heatmap access, since the filter reads the project's events rather than one saved heatmap. Feature-flagged; ignored when the event filter is not enabled for the caller."+ ),filter_test_accounts: zod.boolean().nullish()@@ -161,6 +167,12 @@ export const HeatmapsEventsRetrieveQueryParams = /* @__PURE__ */ zod.object({.min(1).optional().describe("End of the window, inclusive. Relative or absolute 'YYYY-MM-DD'. Defaults to today."),+ events: zod+ .string()+ .nullish()+ .describe(+ "JSON array of event filters (e.g. '[{\"id\": \"purchase\", \"properties\": []}]') to restrict results to sessions in which those events occurred. Each entry needs a string 'id' (the event name) and may carry a 'properties' array of property filters applied to that event, each of type 'event' or 'element'. Several entries are combined with AND: the session must contain a matching event for every entry. At most 10 entries, each with at most 20 property filters. Requires project-wide heatmap access, since the filter reads the project's events rather than one saved heatmap. Feature-flagged; ignored when the event filter is not enabled for the caller."+ ),filter_test_accounts: zod.boolean().nullish()diff --git a/services/mcp/src/tools/generated/web_analytics.ts b/services/mcp/src/tools/generated/web_analytics.tsindex 551b67fc66e6..780d80f1a2ad 100644--- a/services/mcp/src/tools/generated/web_analytics.ts+++ b/services/mcp/src/tools/generated/web_analytics.ts@@ -33,6 +33,7 @@ const heatmapsEvents = (): ToolBase<typeof HeatmapsEventsSchema, Schemas.Heatmapcohort_ids: params.cohort_ids,date_from: params.date_from,date_to: params.date_to,+ events: params.events,filter_test_accounts: params.filter_test_accounts,hide_zero_coordinates: params.hide_zero_coordinates,limit: params.limit,@@ -64,6 +65,7 @@ const heatmapsList = (): ToolBase<typeof HeatmapsListSchema, WithPostHogUrl<Schecohort_ids: params.cohort_ids,date_from: params.date_from,date_to: params.date_to,+ events: params.events,filter_test_accounts: params.filter_test_accounts,hide_zero_coordinates: params.hide_zero_coordinates,limit: params.limit,