: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
fix(heatmaps): group element stats by the chain the response returns (#93046)
Jordan Mryyane2e7ac393b07
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.tsindex 939fb6c808a0..a027ca22501d 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts@@ -1577,9 +1577,9 @@ export function dedupeByChainIdentity(events: ElementsEventType[]): ElementsEvenconst seen = new Set<string>()const deduped: ElementsEventType[] = []for (const event of events) {- // the server hashes the raw chain before attribute filtering, so distinct chains that- // serialize identically after trimming stay distinct; the serialized-content fallback is- // transitional for servers that still return hash as null — delete once that's none of them+ // the hash identifies the chain as the server grouped it, so two rows share it only when+ // the server already counted them as one; the serialized-content fallback is transitional+ // for servers that still return hash as null, delete once that's none of themconst identity = `${event.type}:${event.hash ?? JSON.stringify(event.elements)}`if (seen.has(identity)) {continuediff --git a/posthog/api/element.py b/posthog/api/element.pyindex a2a2b95a8a8e..becc842fe87c 100644--- a/posthog/api/element.py+++ b/posthog/api/element.py@@ -23,12 +23,30 @@ from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATIONfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import ServerTimingsGathered, actionfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange-from posthog.models import Element, Filter+from posthog.models import Element, Filter, Team+from posthog.models.element.chain_query import normalized_elements_chain_exprfrom posthog.models.element.element import build_attributes_filter, chain_to_element_dicts+from posthog.permissions import posthog_feature_flag_enabledfrom posthog.utils import format_query_params_absolute_urltracer = trace.get_tracer(__name__)+CHAIN_NORMALIZATION_FLAG = "heatmaps-clickmap-chain-normalization"+++def chain_normalization_enabled(team: Team) -> bool:+ try:+ return posthog_feature_flag_enabled(+ CHAIN_NORMALIZATION_FLAG,+ str(team.uuid),+ organization_id=team.organization_id,+ team_id=team.id,+ only_evaluate_locally=True,+ )+ except Exception:+ return False++ELEMENT_STATS_TIME_HISTOGRAM = Histogram("element_stats_time_seconds","How long does it take to get element stats?",@@ -70,7 +88,7 @@ class ElementStatsSerializer(serializers.Serializer):count = serializers.IntegerField(help_text="Number of events matching this element chain")hash = serializers.CharField(allow_null=True,- help_text="Stable identity of the raw element chain (hash computed before any attribute filtering), for deduplicating rows across pages",+ help_text="Hash of the chain as the server grouped it; combine with type to deduplicate rows across pages",)type = serializers.CharField(help_text="Event type: $autocapture, $rageclick, or $dead_click")elements = ElementSerializer(many=True, help_text="Parsed elements of the chain, clicked element first")@@ -206,28 +224,35 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):events_filter = self._events_filter(request)- attributes_filter = build_attributes_filter(request.query_params.get("data_attributes", "").split(","))+ wanted_data_attributes = request.query_params.get("data_attributes", "").split(",")+ attributes_filter = build_attributes_filter(wanted_data_attributes)+ chain_expr = (+ normalized_elements_chain_expr(wanted_data_attributes)+ if attributes_filter is not None and chain_normalization_enabled(self.team)+ else ast.Field(chain=["elements_chain"])+ )# HogQL resolves property access per the team's modifiers (materialized# columns, person-on-events mode), so no per-mode handling is needed hereselect = parse_select("""SELECT- elements_chain,+ {chain} AS chain,count() / {sampling_factor} AS occurrences,event AS event_type,- cityHash64(elements_chain) AS chain_hash+ cityHash64(chain) AS chain_hashFROM eventsWHERE event IN {event_types}AND elements_chain != ''AND timestamp >= {date_from}AND timestamp <= {date_to}AND {property_filters}- GROUP BY elements_chain, event+ GROUP BY chain, eventORDER BY occurrences DESCLIMIT {limit} OFFSET {offset}""",placeholders={+ "chain": chain_expr,"sampling_factor": ast.Constant(value=sampling_factor),"event_types": ast.Constant(value=list(events_filter)),"date_from": ast.Constant(value=query_date_from),diff --git a/posthog/api/test/test_element.py b/posthog/api/test/test_element.pyindex 6dcae47e120b..5ed058114a8d 100644--- a/posthog/api/test/test_element.py+++ b/posthog/api/test/test_element.py@@ -393,6 +393,79 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert filtered["results"][0]["elements"][0]["attributes"] == {"attr__data-attr": "signup-cta"}assert filtered["results"][0]["elements"][0]["text"] == "sign up"+ STATS_URL = "/api/element/stats/?paginate_response=true&data_attributes=data-attr"+ NONCES = ("a1b2c3", "d4e5f6", "0a9b8c")++ def _create_autocapture(self, text: str, attributes: dict) -> None:+ _create_event(+ team=self.team,+ elements=[Element(tag_name="button", text=text, order=0, attributes=attributes)],+ event="$autocapture",+ distinct_id="one",+ properties={"$current_url": "http://example.com/demo"},+ )++ @parameterized.expand(+ [+ (+ "collapses_attributes_the_response_discards",+ True,+ [("sign up", {"attr__data-attr": "signup-cta", "attr__ngcspnonce": nonce}) for nonce in NONCES]+ + [("log in", {"attr__data-attr": "login-cta"})],+ [3, 1],+ ),+ (+ "collapses_attribute_values_holding_escaped_quotes",+ True,+ [+ (+ "sign up",+ {+ "attr__data-attr": "signup-cta",+ "attr__style": '--icon: url("/assets/icon.svg")',+ "attr__ngcspnonce": nonce,+ },+ )+ for nonce in NONCES[:2]+ ],+ [2],+ ),+ (+ "leaves_grouping_untouched_while_the_flag_is_off",+ False,+ [("sign up", {"attr__data-attr": "signup-cta", "attr__ngcspnonce": nonce}) for nonce in NONCES],+ [1, 1, 1],+ ),+ ]+ )+ def test_element_stats_chain_normalization(+ self, _name: str, flag_enabled: bool, events: list[tuple[str, dict]], expected_counts: list[int]+ ) -> None:+ _create_person(distinct_ids=["one"], team=self.team, properties={"email": "[email protected]"})+ for text, attributes in events:+ self._create_autocapture(text, attributes)++ with mock.patch("posthog.api.element.posthog_feature_flag_enabled", return_value=flag_enabled):+ results = self.client.get(self.STATS_URL).json()["results"]++ assert [row["count"] for row in results] == expected_counts+ assert results[0]["elements"][0]["text"] == "sign up"+ assert results[0]["elements"][0]["attributes"] == {"attr__data-attr": "signup-cta"}++ @mock.patch("posthog.api.element.posthog_feature_flag_enabled", return_value=True)+ def test_element_stats_keeps_requested_data_attributes_distinct(self, _flag: mock.MagicMock) -> None:+ _create_person(distinct_ids=["one"], team=self.team, properties={"email": "[email protected]"})+ self._create_autocapture("sign up", {"attr__data-attr": "signup-cta"})+ self._create_autocapture("sign up", {"attr__data-attr": "signup-secondary"})++ results = self.client.get(self.STATS_URL).json()["results"]++ assert len(results) == 2+ assert sorted(row["elements"][0]["attributes"]["attr__data-attr"] for row in results) == [+ "signup-cta",+ "signup-secondary",+ ]+def test_element_stats_returns_stable_chain_hashes(self) -> None:self._setup_events()diff --git a/posthog/models/element/chain_query.py b/posthog/models/element/chain_query.pynew file mode 100644index 000000000000..1e8e9edcaaa8--- /dev/null+++ b/posthog/models/element/chain_query.py@@ -0,0 +1,33 @@+import re++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr++from posthog.models.element.element import wanted_attribute_entries++_ATTRIBUTE_KEY_CHARS = r"[a-zA-Z0-9_:.\-]"+_ATTRIBUTE_PAIR_PATTERN = rf'attr__{_ATTRIBUTE_KEY_CHARS}+="(?:[^"\\]|\\.)*"'+_KEPT_ATTRIBUTE_SENTINEL = "\x01"++_NORMALIZED_CHAIN_SQL = (+ "replaceRegexpAll(replaceRegexpAll(replaceRegexpAll("+ "elements_chain, {protect}, {protect_with}), {strip}, ''), {restore}, {restore_with})"+)+++def normalized_elements_chain_expr(wanted_data_attributes: list[str]) -> ast.Expr:+ entries = wanted_attribute_entries(wanted_data_attributes)+ if not entries:+ return ast.Field(chain=["elements_chain"])++ kept = "|".join(re.escape(entry).replace(r"\*", f"{_ATTRIBUTE_KEY_CHARS}*") for entry in entries)+ return parse_expr(+ _NORMALIZED_CHAIN_SQL,+ placeholders={+ "protect": ast.Constant(value=rf'attr__({kept})="'),+ "protect_with": ast.Constant(value=_KEPT_ATTRIBUTE_SENTINEL + r'\1="'),+ "strip": ast.Constant(value=_ATTRIBUTE_PAIR_PATTERN),+ "restore": ast.Constant(value=_KEPT_ATTRIBUTE_SENTINEL),+ "restore_with": ast.Constant(value="attr__"),+ },+ )diff --git a/posthog/models/element/element.py b/posthog/models/element/element.pyindex 2fb3cca88d22..94fb1cc5d063 100644--- a/posthog/models/element/element.py+++ b/posthog/models/element/element.py@@ -97,6 +97,10 @@ def chain_to_elements(chain: str) -> list[Element]:_MAX_DATA_ATTRIBUTES = 50+def wanted_attribute_entries(wanted_data_attributes: list[str]) -> list[str]:+ return [attribute.strip() for attribute in wanted_data_attributes if attribute.strip()][:_MAX_DATA_ATTRIBUTES]++def _glob_matcher(pattern: str) -> Callable[[str], bool]:"""Returns a matcher for a glob pattern where each * matches any run of characters.Linear-time string scanning, never regex, so caller-supplied patterns can't trigger@@ -125,7 +129,7 @@ def build_attributes_filter(wanted_data_attributes: list[str]) -> Callable[[str]* wildcards (e.g. data-*). Entries beyond the first 50 are ignored to bound per-key cost.Returns None when there is nothing to filter by."""- entries = [attribute.strip() for attribute in wanted_data_attributes if attribute.strip()][:_MAX_DATA_ATTRIBUTES]+ entries = wanted_attribute_entries(wanted_data_attributes)if not entries:return Nonediff --git a/posthog/permissions.py b/posthog/permissions.pyindex 86e89a9d88cd..6beb3c5c9861 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -1065,6 +1065,7 @@ def posthog_feature_flag_value(*,organization_id: str | uuid.UUID,team_id: int | None = None,+ only_evaluate_locally: bool = False,) -> bool | None:"""Server-side check of a PostHog-internal gating flag with org/project group context.@@ -1089,7 +1090,7 @@ def posthog_feature_flag_value(distinct_id,groups=groups,group_properties=group_properties,- only_evaluate_locally=False,+ only_evaluate_locally=only_evaluate_locally,send_feature_flag_events=False,)@@ -1100,6 +1101,7 @@ def posthog_feature_flag_enabled(*,organization_id: str | uuid.UUID,team_id: int | None = None,+ only_evaluate_locally: bool = False,) -> bool:return bool(posthog_feature_flag_value(@@ -1107,6 +1109,7 @@ def posthog_feature_flag_enabled(distinct_id,organization_id=organization_id,team_id=team_id,+ only_evaluate_locally=only_evaluate_locally,))diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex d4254e489ad1..44bd7b0f6774 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -181,7 +181,7 @@ export interface ElementStatsApi {/** Number of events matching this element chain */count: number/**- * Stable identity of the raw element chain (hash computed before any attribute filtering), for deduplicating rows across pages+ * Hash of the chain as the server grouped it; combine with type to deduplicate rows across pages* @nullable*/hash: string | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6c4936048010..98ea45cb9fc7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29893,7 +29893,7 @@ export namespace Schemas {/** Number of events matching this element chain */count: number;/**- * Stable identity of the raw element chain (hash computed before any attribute filtering), for deduplicating rows across pages+ * Hash of the chain as the server grouped it; combine with type to deduplicate rows across pages* @nullable*/hash: string | null;