: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): Add cohort filtering to heatmaps (#59909)
Jordan Mryyan81265f3d9164
diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.tsindex 7b86f032f268..91bfc8cf273f 100644--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts@@ -172,7 +172,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([actions.setIsReady(false)- const { date_from, date_to, filter_test_accounts } = values.commonFilters+ const { date_from, date_to, filter_test_accounts, cohort_ids } = values.commonFiltersconst { type, aggregation } = values.heatmapFilters// toolbar fetch collapses queryparams but this URL has multiple with the same name@@ -187,6 +187,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([viewport_width_max: values.viewportRange.max,aggregation,filter_test_accounts,+ cohort_ids: cohort_ids && cohort_ids.length > 0 ? cohort_ids : undefined,},'?')}`@@ -224,7 +225,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([await breakpoint(100)- const { date_from, date_to, filter_test_accounts } = values.commonFilters+ const { date_from, date_to, filter_test_accounts, cohort_ids } = values.commonFiltersconst { type } = values.heatmapFiltersconst apiURL = `/api/heatmap/events/${encodeParams(@@ -237,6 +238,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([viewport_width_min: values.viewportRange.min,viewport_width_max: values.viewportRange.max,filter_test_accounts,+ cohort_ids: cohort_ids && cohort_ids.length > 0 ? cohort_ids : undefined,points: JSON.stringify(area.points),},'?'@@ -413,7 +415,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([return}- const { date_from, date_to, filter_test_accounts } = values.commonFilters+ const { date_from, date_to, filter_test_accounts, cohort_ids } = values.commonFiltersconst { type } = values.heatmapFiltersconst nextOffset = currentEvents.results.length@@ -427,6 +429,7 @@ export const heatmapDataLogic = kea<heatmapDataLogicType>([viewport_width_min: values.viewportRange.min,viewport_width_max: values.viewportRange.max,filter_test_accounts,+ cohort_ids: cohort_ids && cohort_ids.length > 0 ? cohort_ids : undefined,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 cfea244772ac..6bd5a969a1e1 100644--- a/frontend/src/lib/components/heatmaps/types.ts+++ b/frontend/src/lib/components/heatmaps/types.ts@@ -2,6 +2,7 @@ export type CommonFilters = {date_from?: string | nulldate_to?: string | nullfilter_test_accounts?: boolean+ cohort_ids?: number[]}export type HeatmapKind = 'click' | 'rageclick' | 'mousemove' | 'scrolldepth'diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 70a21859c97f..e3702742d942 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -195,6 +195,7 @@ export const FEATURE_FLAGS = {issues related to this and want to know the impact of having it on vs. off. */EXPERIMENTAL_DASHBOARD_ITEM_RENDERING: 'experimental-dashboard-item-rendering', // owner: @thmsobrmlr #team-product-analyticsGATEWAY_PERSONAL_API_KEY: 'gateway-personal-api-key', // owner: #team-platform-features+ HEATMAPS_COHORT_FILTER: 'heatmaps-cohort-filter', // owner: #team-web-analyticsIMPROVED_COOKIELESS_MODE: 'improved-cookieless-mode', // owner: #team-web-analyticsLINEAGE_DEPENDENCY_VIEW: 'lineage-dependency-view', // owner: #team-data-modelingMEMBERS_CAN_USE_PERSONAL_API_KEYS: 'members-can-use-personal-api-keys', // owner: @yasen-posthog #team-platform-featuresdiff --git a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx b/frontend/src/scenes/heatmaps/components/FilterPanel.tsxindex 14a77005a819..0d4917299509 100644--- a/frontend/src/scenes/heatmaps/components/FilterPanel.tsx+++ b/frontend/src/scenes/heatmaps/components/FilterPanel.tsx@@ -9,12 +9,30 @@ import { heatmapDataLogic } from 'lib/components/heatmaps/heatmapDataLogic'import { HeatmapsSettings } from 'lib/components/heatmaps/HeatMapsSettings'import { SectionSetting } from 'lib/components/heatmaps/HeatMapsSettings'import { heatmapDateOptions } from 'lib/components/IframedToolbarBrowser/utils'+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LoadingBar } from 'lib/lemon-ui/LoadingBar'import { Popover } from 'lib/lemon-ui/Popover'import { inStorybook, inStorybookTestRunner } from 'lib/utils'+import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from 'scenes/feature-flags/cohortPickerProps'import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter'-import { HeatmapType } from '~/types'+import { AnyPropertyFilter, CohortPropertyFilter, HeatmapType, PropertyFilterType, PropertyOperator } from '~/types'++const cohortIdsToPropertyFilters = (ids: number[]): AnyPropertyFilter[] =>+ ids.map((id) => ({+ type: PropertyFilterType.Cohort,+ key: 'id',+ value: id,+ operator: PropertyOperator.In,+ }))++const propertyFiltersToCohortIds = (filters: AnyPropertyFilter[]): number[] =>+ filters+ .filter((f): f is CohortPropertyFilter => f.type === PropertyFilterType.Cohort)+ .map((f) => f.value)+ .filter((v): v is number => typeof v === 'number')const useDebounceLoading = (loading: boolean, delay = 200): boolean => {const [debouncedLoading, setDebouncedLoading] = useState(false)@@ -122,6 +140,8 @@ export function FilterPanel({heatmapDataLogic({ context: 'in-app' }))+ const cohortFilterEnabled = useFeatureFlag('HEATMAPS_COHORT_FILTER')+const debouncedLoading = useDebounceLoading(rawHeatmapLoading ?? false)// KLUDGE: the loading bar flaps in visual regression tests,@@ -145,6 +165,25 @@ export function FilterPanel({}}dateOptions={heatmapDateOptions}/>+ {cohortFilterEnabled && (+ <div className="mt-2 md:mt-0">+ <PropertyFilters+ pageKey="heatmap-cohorts"+ propertyFilters={cohortIdsToPropertyFilters(commonFilters?.cohort_ids ?? [])}+ onChange={(filters) =>+ setCommonFilters?.({+ ...commonFilters,+ cohort_ids: propertyFiltersToCohortIds(filters),+ })+ }+ taxonomicGroupTypes={[TaxonomicFilterGroupType.Cohorts]}+ buttonText="Filter by cohort"+ addText="Add cohort filter"+ buttonSize="small"+ {...COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS}+ />+ </div>+ )}<div className="mt-2 md:mt-0"><Popoveroverlay={diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex 238b1021c32a..411f6e2f5334 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -6,6 +6,7 @@ from django.core.exceptions import FieldErrorfrom django.db.models import Qfrom django.http import HttpResponse+import posthoganalyticsfrom rest_framework import request, response, serializers, status, viewsetsfrom posthog.schema import DateRange, HogQLFilters, HogQLQueryResponse, ProductKey@@ -25,7 +26,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.auth import ExportRendererAuthenticationfrom posthog.clickhouse.query_tagging import Feature, tag_queries-from posthog.models import User+from posthog.models import Cohort, Team, Userfrom posthog.models.activity_logging.activity_log import Detail, log_activityfrom posthog.rate_limit import (AIBurstRateThrottle,@@ -42,6 +43,30 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import generate_heaSTALE_PROCESSING_THRESHOLD = timedelta(minutes=10)+HEATMAPS_COHORT_FILTER_FLAG = "heatmaps-cohort-filter"+++def _heatmaps_cohort_filter_enabled(user: User, team: Team) -> bool:+ distinct_id = getattr(user, "distinct_id", None)+ if not distinct_id:+ return False+ try:+ return bool(+ posthoganalytics.feature_enabled(+ HEATMAPS_COHORT_FILTER_FLAG,+ str(distinct_id),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ send_feature_flag_events=False,+ )+ )+ except Exception:+ return False++DEFAULT_QUERY = """select pointer_target_fixed, pointer_relative_x, client_y, {aggregation_count}from (@@ -109,6 +134,30 @@ class HeatmapsRequestSerializer(serializers.Serializer):)filter_test_accounts = serializers.BooleanField(required=False, default=None, allow_null=True)hide_zero_coordinates = serializers.BooleanField(required=False, default=True)+ cohort_ids = serializers.CharField(required=False, allow_null=True, allow_blank=True)++ def validate_cohort_ids(self, value: str | None) -> list[int]:+ if value is None or value == "":+ return []+ try:+ cohort_ids = loads(value)+ except JSONDecodeError:+ raise serializers.ValidationError("cohort_ids must be valid JSON")+ if not isinstance(cohort_ids, list) or not all(isinstance(cid, int) for cid in cohort_ids):+ raise serializers.ValidationError("cohort_ids must be a JSON array of integers")+ if not cohort_ids:+ return []+ team_cohort_ids = set(+ Cohort.objects.filter(+ id__in=cohort_ids,+ team__project_id=self.context["team"].project_id,+ deleted=False,+ ).values_list("id", flat=True)+ )+ missing = [cid for cid in cohort_ids if cid not in team_cohort_ids]+ if missing:+ raise serializers.ValidationError(f"Cohort(s) not found or deleted: {missing}")+ return cohort_idsdef validate_date(self, value, label: Literal["date_from", "date_to"]) -> date:try:@@ -240,8 +289,11 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):aggregation = request_serializer.validated_data.pop("aggregation")hide_zero_coordinates = request_serializer.validated_data.pop("hide_zero_coordinates", True)- placeholders: dict[str, Expr] = {k: Constant(value=v) for k, v in request_serializer.validated_data.items()}- placeholders["date_to"] = placeholders.get("date_to", Constant(value=date.today().strftime("%Y-%m-%d")))+ if request_serializer.validated_data.get("cohort_ids") and not _heatmaps_cohort_filter_enabled(+ cast(User, request.user), self.team+ ):+ request_serializer.validated_data.pop("cohort_ids")+ placeholders = self._build_placeholders(request_serializer.validated_data)is_scrolldepth_query = placeholders.get("type", None) == Constant(value="scrolldepth")raw_query = SCROLL_DEPTH_QUERY if is_scrolldepth_query else DEFAULT_QUERY@@ -299,6 +351,18 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):right=events_select,)+ @staticmethod+ def _build_placeholders(validated_data: dict[str, Any]) -> dict[str, Expr]:+ placeholders: dict[str, Expr] = {}+ for key, value in validated_data.items():+ if key == "cohort_ids":+ if value:+ placeholders[key] = ast.Array(exprs=[Constant(value=cid) for cid in value])+ continue+ placeholders[key] = Constant(value=value)+ placeholders.setdefault("date_to", Constant(value=date.today().strftime("%Y-%m-%d")))+ return placeholders+@staticmethoddef _predicate_expressions(placeholders: dict[str, Expr]) -> List[ast.Expr]: # noqa: UP006predicate_expressions: list[ast.Expr] = []@@ -322,6 +386,17 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):parse_expr(predicate_mapping[predicate_key], {predicate_key: placeholders[predicate_key]}))+ cohort_ids_expr = placeholders.get("cohort_ids")+ if isinstance(cohort_ids_expr, ast.Array):+ for cohort_id_expr in cohort_ids_expr.exprs:+ predicate_expressions.append(+ parse_expr(+ "distinct_id IN (SELECT distinct_id FROM person_distinct_ids "+ "WHERE person_id IN COHORT {cohort_id})",+ {"cohort_id": cohort_id_expr},+ )+ )+if len(predicate_expressions) == 0:raise serializers.ValidationError("must always generate some filter conditions")@@ -377,9 +452,12 @@ class HeatmapViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):points = validated_data.pop("points")validated_data.pop("aggregation", None)validated_data.pop("hide_zero_coordinates", None)+ if validated_data.get("cohort_ids") and not _heatmaps_cohort_filter_enabled(+ cast(User, request.user), self.team+ ):+ validated_data.pop("cohort_ids")- placeholders: dict[str, Expr] = {k: Constant(value=v) for k, v in validated_data.items()}- placeholders["date_to"] = placeholders.get("date_to", Constant(value=date.today().strftime("%Y-%m-%d")))+ placeholders = self._build_placeholders(validated_data)exprs = self._predicate_expressions(placeholders)