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.

feat(toolbar): serialize element stats without models and trim attributes (#67755)

Paul D'Ambra048b9b0239a5
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
index d0b780f9d877..a84798fc90aa 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
@@ -15,7 +15,7 @@ function statsRow(overrides: Partial<ElementsEventType>): ElementsEventType {
describe('dedupeByChainIdentity', () => {
const cases = [
{
- name: 'keeps distinct chains even though the API returns hash null for every row',
+ name: 'keeps distinct chains when a legacy server returns hash null',
events: [
statsRow({ elements: [{ tag_name: 'button', attributes: {} }] as ElementsEventType['elements'] }),
statsRow({ elements: [{ tag_name: 'a', attributes: {} }] as ElementsEventType['elements'] }),
@@ -23,7 +23,7 @@ describe('dedupeByChainIdentity', () => {
expectedCount: 2,
},
{
- name: 'drops a chain repeated across paginated pages, keeping the first occurrence',
+ name: 'drops a null-hash chain repeated across paginated pages, keeping the first occurrence',
events: [statsRow({ count: 10 }), statsRow({ count: 3 })],
expectedCount: 1,
},
@@ -32,6 +32,16 @@ describe('dedupeByChainIdentity', () => {
events: [statsRow({ type: '$autocapture' }), statsRow({ type: '$rageclick' })],
expectedCount: 2,
},
+ {
+ name: 'keeps distinct hashes even when attribute trimming made the chains serialize identically',
+ events: [statsRow({ hash: 'abc123' }), statsRow({ hash: 'def456' })],
+ expectedCount: 2,
+ },
+ {
+ name: 'drops a repeated hash across paginated pages, keeping the first occurrence',
+ events: [statsRow({ hash: 'abc123', count: 10 }), statsRow({ hash: 'abc123', count: 3 })],
+ expectedCount: 1,
+ },
]
it.each(cases)('$name', ({ events, expectedCount }) => {
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
index 41dd39d51b24..303bc38834ed 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
@@ -291,6 +291,9 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
paginate_response: true,
sampling_factor: values.samplingFactor,
limit: ELEMENT_STATS_PAGE_LIMIT,
+ // the matchers only read the configured data attributes from each
+ // element's attributes map, so let the server drop the rest
+ data_attributes: values.wantedDataAttributes.join(','),
},
options
)
@@ -331,6 +334,12 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
],
elementCount: [(s) => [s.countedElements], (countedElements) => countedElements.length],
loadedElementStatsCount: [(s) => [s.elementStats], (elementStats) => elementStats?.results?.length ?? 0],
+ // isTooSimple always reads attr__data-attr, so request it alongside the configured data
+ // attributes — first, so it survives the server's entry cap however many are configured
+ wantedDataAttributes: [
+ () => [toolbarConfigLogic.selectors.dataAttributes],
+ (dataAttributes: string[]): string[] => Array.from(new Set(['data-attr', ...dataAttributes])),
+ ],
clickCount: [
(s) => [s.countedElements],
(countedElements) => (countedElements ? countedElements.map((e) => e.count).reduce((a, b) => a + b, 0) : 0),
@@ -661,9 +670,10 @@ export function dedupeByChainIdentity(events: ElementsEventType[]): ElementsEven
const seen = new Set<string>()
const deduped: ElementsEventType[] = []
for (const event of events) {
- // /api/element/stats returns hash as null for every row, so the chain content is the
- // only usable row identity
- const identity = `${event.type}:${JSON.stringify(event.elements)}`
+ // 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
+ const identity = `${event.type}:${event.hash ?? JSON.stringify(event.elements)}`
if (seen.has(identity)) {
continue
}
diff --git a/posthog/api/element.py b/posthog/api/element.py
index b95900030a3e..137f8938f84e 100644
--- a/posthog/api/element.py
+++ b/posthog/api/element.py
@@ -2,7 +2,7 @@ from typing import Literal
from django.conf import settings
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import OpenApiParameter, extend_schema
from opentelemetry import trace
from prometheus_client import Histogram
from rest_framework import request, response, serializers, viewsets
@@ -15,7 +15,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import ServerTimingsGathered, action
from posthog.clickhouse.client import sync_execute
from posthog.models import Element, Filter
-from posthog.models.element.element import chain_to_elements
+from posthog.models.element.element import build_attributes_filter, chain_to_element_dicts
from posthog.models.element.sql import GET_ELEMENTS, GET_VALUES
from posthog.models.property.util import parse_prop_grouped_clauses
from posthog.queries.query_date_range import QueryDateRange
@@ -53,10 +53,19 @@ class ElementSerializer(serializers.ModelSerializer):
class ElementStatsSerializer(serializers.Serializer):
- count = serializers.IntegerField()
- hash = serializers.CharField(allow_null=True)
- type = serializers.CharField()
- elements = ElementSerializer(many=True)
+ 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",
+ )
+ 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")
+
+
+class ElementStatsResponseSerializer(serializers.Serializer):
+ results = ElementStatsSerializer(many=True, help_text="Element chains with event counts, ordered by count")
+ next = serializers.CharField(allow_null=True, help_text="URL for the next page of results, if any")
+ previous = serializers.CharField(allow_null=True, help_text="URL for the previous page of results, if any")
@extend_schema(extensions={"x-product": ProductKey.PRODUCT_ANALYTICS})
@@ -68,6 +77,38 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
queryset = Element.objects.all()
serializer_class = ElementSerializer
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "include",
+ type=str,
+ many=True,
+ description="Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three.",
+ ),
+ OpenApiParameter("limit", type=int, description="Maximum rows per page"),
+ OpenApiParameter("offset", type=int, description="Pagination offset"),
+ OpenApiParameter("sampling_factor", type=float, description="Sampling factor between 0 and 1"),
+ OpenApiParameter(
+ "data_attributes",
+ type=str,
+ description=(
+ "Comma-separated data attribute names (wildcards allowed, e.g. data-*). When provided, "
+ "each element's attributes map is filtered to matching attr__* keys, shrinking the response."
+ ),
+ ),
+ OpenApiParameter(
+ "date_from",
+ type=str,
+ description="Start of the date range (e.g. -7d, 2024-01-01). Defaults to last 7 days.",
+ ),
+ OpenApiParameter(
+ "date_to",
+ type=str,
+ description="End of the date range (e.g. 2024-01-31). Defaults to now.",
+ ),
+ ],
+ responses=ElementStatsResponseSerializer,
+ )
@action(methods=["GET"], detail=False)
def stats(self, request: request.Request, **kwargs) -> response.Response:
"""
@@ -109,6 +150,8 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
events_filter = self._events_filter(request)
+ attributes_filter = build_attributes_filter(request.query_params.get("data_attributes", "").split(","))
+
# unless someone is using this as an API client, this is only for the toolbar,
# which only ever queries date range, event type, and URL
prop_filters, prop_filter_params = parse_prop_grouped_clauses(
@@ -144,23 +187,19 @@ class ElementViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
},
)
- with (
- timer("prepare_for_serialization"),
- tracer.start_as_current_span("elements_api_stats.prepare_for_serialization"),
- ):
- elements_data = [
+ with timer("serialize_elements"), tracer.start_as_current_span("elements_api_stats.serialize_elements"):
+ # parses chains straight to response dicts (shaped exactly like
+ # ElementStatsSerializer output, which stays as the declared schema)
+ serialized_elements = [
{
- "count": elements[1],
- "hash": None,
- "type": elements[2],
- "elements": chain_to_elements(elements[0]),
+ "count": int(count),
+ "hash": f"{chain_hash:x}",
+ "type": event_type,
+ "elements": chain_to_element_dicts(chain, attributes_filter),
}
- for elements in result[:limit]
+ for chain, count, event_type, chain_hash in result[:limit]
]
- with timer("serialize_elements"), tracer.start_as_current_span("elements_api_stats.serialize_elements"):
- serialized_elements = ElementStatsSerializer(elements_data, many=True).data
-
span.set_attribute("result_count", len(serialized_elements))
ELEMENT_STATS_RESULT_COUNT_HISTOGRAM.labels(limit=limit).observe(len(serialized_elements))
diff --git a/posthog/api/test/test_element.py b/posthog/api/test/test_element.py
index 6b88bb4adfa5..b12809c02470 100644
--- a/posthog/api/test/test_element.py
+++ b/posthog/api/test/test_element.py
@@ -10,6 +10,7 @@ from posthog.test.base import (
_create_person,
snapshot_postgres_queries,
)
+from unittest import mock
from django.test import override_settings
@@ -21,7 +22,7 @@ from posthog.models import Element, ElementGroup, Organization
expected_autocapture_data_response_results: list[dict] = [
{
"count": 3,
- "hash": None,
+ "hash": mock.ANY,
"type": "$autocapture",
"elements": [
{
@@ -50,7 +51,7 @@ expected_autocapture_data_response_results: list[dict] = [
},
{
"count": 2,
- "hash": None,
+ "hash": mock.ANY,
"type": "$autocapture",
"elements": [
{
@@ -82,7 +83,7 @@ expected_autocapture_data_response_results: list[dict] = [
expected_rage_click_data_response_results: list[dict] = [
{
"count": 1,
- "hash": None,
+ "hash": mock.ANY,
"type": "$rageclick",
"elements": [
{
@@ -299,6 +300,50 @@ class TestElement(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
limit_to_one_results_page_three = page_three_response_json["results"]
assert limit_to_one_results_page_three == [expected_rage_click_data_response_results[0]]
+ def test_element_stats_filters_attributes_to_requested_data_attributes(self) -> None:
+ _create_person(distinct_ids=["one"], team=self.team, properties={"email": "[email protected]"})
+ _create_event(
+ team=self.team,
+ elements=[
+ Element(
+ tag_name="button",
+ text="sign up",
+ order=0,
+ attributes={"attr__data-attr": "signup-cta", "attr__aria-label": "call to action"},
+ )
+ ],
+ event="$autocapture",
+ distinct_id="one",
+ properties={"$current_url": "http://example.com/demo"},
+ )
+
+ unfiltered = self.client.get("/api/element/stats/?paginate_response=true").json()
+ assert unfiltered["results"][0]["elements"][0]["attributes"] == {
+ "attr__data-attr": "signup-cta",
+ "attr__aria-label": "call to action",
+ }
+
+ filtered = self.client.get("/api/element/stats/?paginate_response=true&data_attributes=data-attr").json()
+ assert filtered["results"][0]["elements"][0]["attributes"] == {"attr__data-attr": "signup-cta"}
+ assert filtered["results"][0]["elements"][0]["text"] == "sign up"
+
+ def test_element_stats_returns_stable_chain_hashes(self) -> None:
+ self._setup_events()
+
+ first = self.client.get("/api/element/stats/?paginate_response=true").json()["results"]
+ second = self.client.get("/api/element/stats/?paginate_response=true").json()["results"]
+
+ hashes = [row["hash"] for row in first]
+ assert all(isinstance(h, str) and h for h in hashes)
+ assert hashes == [row["hash"] for row in second]
+ assert len({(row["type"], row["hash"]) for row in first}) == len(first)
+
+ autocapture_event_1 = next(
+ row for row in first if row["type"] == "$autocapture" and row["elements"][0]["text"] == "event 1"
+ )
+ rageclick_event_1 = next(row for row in first if row["type"] == "$rageclick")
+ assert autocapture_event_1["hash"] == rageclick_event_1["hash"]
+
def test_element_stats_does_not_allow_non_numeric_limit(self) -> None:
response = self.client.get(f"/api/element/stats/?limit=not-a-number")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/posthog/models/element/element.py b/posthog/models/element/element.py
index 0948daaf3982..2fb3cca88d22 100644
--- a/posthog/models/element/element.py
+++ b/posthog/models/element/element.py
@@ -1,4 +1,5 @@
import re
+from collections.abc import Callable
from django.contrib.postgres.fields import ArrayField
from django.db import models
@@ -60,10 +61,6 @@ def elements_to_string(elements: list[Element]) -> str:
def chain_to_elements(chain: str) -> list[Element]:
"""
Converts an elements chain string into a list of Element objects.
- Since for example in the elements API this could be called on a large list
- which has a limited number of unique elements_chains,
- we have a limited LRU in-memory cache
- conversion is completely deterministic, so can be cached indefinitely
"""
elements = []
for idx, el_string in enumerate(re.findall(split_chain_regex, chain)):
@@ -95,3 +92,105 @@ def chain_to_elements(chain: str) -> list[Element]:
elements.append(element)
return elements
+
+
+_MAX_DATA_ATTRIBUTES = 50
+
+
+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
+ catastrophic backtracking."""
+ head, *middle, tail = pattern.split("*")
+
+ def matches(key: str) -> bool:
+ if not key.startswith(head) or not key.endswith(tail):
+ return False
+ position = len(head)
+ end = len(key) - len(tail)
+ for segment in middle:
+ found = key.find(segment, position, end)
+ if found == -1:
+ return False
+ position = found + len(segment)
+ return position <= end
+
+ return matches
+
+
+def build_attributes_filter(wanted_data_attributes: list[str]) -> Callable[[str], bool] | None:
+ """
+ Builds a matcher for attr__ keys matching the configured data attributes, mirroring the
+ toolbar's matchesDataAttribute: keys carry an attr__ prefix and configured names may use
+ * 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]
+ if not entries:
+ return None
+
+ exact_keys = frozenset(f"attr__{entry}" for entry in entries if "*" not in entry)
+ glob_matchers = [_glob_matcher(f"attr__{entry}") for entry in entries if "*" in entry]
+
+ def matches(key: str) -> bool:
+ if key in exact_keys:
+ return True
+ for matcher in glob_matchers:
+ if matcher(key):
+ return True
+ return False
+
+ return matches
+
+
+def chain_to_element_dicts(chain: str, attributes_filter: Callable[[str], bool] | None = None) -> list[dict]:
+ """
+ Converts an elements chain string into serialized element dicts, shaped exactly like
+ ElementSerializer output but without instantiating Element models, so the elements API
+ can serialize large pages cheaply. attributes_filter optionally restricts the attributes
+ map to matching keys (see build_attributes_filter).
+ """
+ element_dicts: list[dict] = []
+ for idx, el_string in enumerate(split_chain_regex.findall(chain)):
+ el_string_match = split_class_attributes.search(el_string)
+ tag_part = el_string_match.group(1) if el_string_match else ""
+ attrs_part = el_string_match.group(3) if el_string_match else None
+
+ element: dict = {
+ "text": None,
+ "tag_name": None,
+ "attr_class": None,
+ "href": None,
+ "attr_id": None,
+ "nth_child": None,
+ "nth_of_type": None,
+ "attributes": {},
+ "order": idx,
+ }
+
+ if tag_part:
+ tag_and_class = tag_part.split(".", 1)
+ element["tag_name"] = tag_and_class[0]
+ if len(tag_and_class) > 1:
+ element["attr_class"] = [cl for cl in tag_and_class[1].split(".") if cl != ""]
+
+ if attrs_part:
+ for attribute_match in parse_attributes_regex.finditer(attrs_part):
+ key = attribute_match.group("key")
+ value = attribute_match.group("value")
+ if key == "href":
+ element["href"] = value
+ elif key == "nth-child":
+ element["nth_child"] = int(value)
+ elif key == "nth-of-type":
+ element["nth_of_type"] = int(value)
+ elif key == "text":
+ element["text"] = value
+ elif key == "attr_id":
+ element["attr_id"] = value
+ elif key:
+ if attributes_filter is None or attributes_filter(key):
+ element["attributes"][key] = value
+
+ element_dicts.append(element)
+ return element_dicts
diff --git a/posthog/models/element/sql.py b/posthog/models/element/sql.py
index 895efa80517e..518c96a95dd7 100644
--- a/posthog/models/element/sql.py
+++ b/posthog/models/element/sql.py
@@ -1,6 +1,6 @@
GET_ELEMENTS = """
SELECT
- elements_chain, count() / %(sampling_factor)s as count, event as event_type
+ elements_chain, count() / %(sampling_factor)s as count, event as event_type, cityHash64(elements_chain) as chain_hash
FROM events
SAMPLE %(sampling_factor)s
WHERE
diff --git a/posthog/test/test_element_model.py b/posthog/test/test_element_model.py
index f4e54974ca56..71b4cb478afc 100644
--- a/posthog/test/test_element_model.py
+++ b/posthog/test/test_element_model.py
@@ -1,6 +1,12 @@
+from typing import cast
+
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from parameterized import parameterized
+
+from posthog.api.element import ElementSerializer
from posthog.models.element import Element, chain_to_elements, elements_to_string
+from posthog.models.element.element import build_attributes_filter, chain_to_element_dicts
class TestElement(ClickhouseTestMixin, BaseTest):
@@ -64,6 +70,72 @@ class TestElement(ClickhouseTestMixin, BaseTest):
self.assertEqual(elements[1].attr_class, ["btn", "btn-primary"])
self.assertEqual(elements[3].attr_id, "nested")
+ @parameterized.expand(
+ [
+ (
+ "escaped quotes and semicolons in attributes",
+ r'a.small:data-attr="something \" that; could mess up"href="/a-url"nth-child="1"nth-of-type="0"text="bla bla";button.btn.btn-primary:nth-child="0"nth-of-type="0"',
+ ),
+ (
+ "attr__ prefixed production-shaped chain",
+ 'svg.LemonIcon.text-3xl:attr__class="LemonIcon text-3xl"attr__fill="currentColor"attr__width="100%"nth-child="1"nth-of-type="1";div:attr_id="nested"nth-child="0"nth-of-type="0"',
+ ),
+ ("broken class names", "a........small"),
+ ("empty chain", ""),
+ ]
+ )
+ def test_chain_to_element_dicts_matches_serialized_models(self, _name: str, chain: str) -> None:
+ via_models = cast(list[dict], ElementSerializer(chain_to_elements(chain), many=True).data)
+ assert chain_to_element_dicts(chain) == via_models
+
+ @parameterized.expand(
+ [
+ ("exact name", ["data-attr"], {"attr__data-attr": "x"}),
+ ("wildcard", ["data-*"], {"attr__data-attr": "x", "attr__data-tracking-id": "y"}),
+ ("no match keeps other fields", ["data-nope"], {}),
+ ("multiple wildcards, matching the toolbar's semantics", ["data-*ing-*"], {"attr__data-tracking-id": "y"}),
+ (
+ "wildcard and exact entries together",
+ ["data-*-id", "data-attr"],
+ {"attr__data-attr": "x", "attr__data-tracking-id": "y"},
+ ),
+ (
+ "lone wildcard matches every attribute, like the toolbar's regex",
+ ["*"],
+ {
+ "attr__class": "small",
+ "attr__data-attr": "x",
+ "attr__data-tracking-id": "y",
+ "attr__style": "color: red",
+ },
+ ),
+ ]
+ )
+ def test_chain_to_element_dicts_filters_attributes(
+ self, _name: str, wanted: list[str], expected_attributes: dict
+ ) -> None:
+ chain = 'a.small:attr__class="small"attr__data-attr="x"attr__data-tracking-id="y"attr__style="color: red"href="/a-url"nth-child="1"nth-of-type="1"'
+ element_dicts = chain_to_element_dicts(chain, build_attributes_filter(wanted))
+ assert element_dicts[0]["attributes"] == expected_attributes
+ assert element_dicts[0]["href"] == "/a-url"
+ assert element_dicts[0]["attr_class"] == ["small"]
+
+ def test_build_attributes_filter_caps_entry_count(self) -> None:
+ many_attrs = [f"data-attr-{i}" for i in range(100)]
+ matcher = build_attributes_filter(many_attrs)
+ assert matcher is not None
+ assert matcher("attr__data-attr-0")
+ assert not matcher("attr__data-attr-99")
+
+ def test_build_attributes_filter_normalizes_entries_before_capping(self) -> None:
+ matcher = build_attributes_filter([" ", ""] * 10 + [f"data-{i}" for i in range(50)])
+ assert matcher is not None
+ assert matcher("attr__data-49")
+
+ @parameterized.expand([("empty list", []), ("blank entries only", [" ", ""])])
+ def test_build_attributes_filter_returns_none_when_nothing_to_filter(self, _name: str, wanted: list[str]) -> None:
+ assert build_attributes_filter(wanted) is None
+
def test_broken_class_names(self):
elements = chain_to_elements("a........small")
self.assertEqual(elements[0].tag_name, "a")
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 3e8ddde5be85..5e12ecfeccde 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -176,6 +176,35 @@ export interface PatchedElementApi {
order?: number | null
}
+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
+ * @nullable
+ */
+ hash: string | null
+ /** Event type: $autocapture, $rageclick, or $dead_click */
+ type: string
+ /** Parsed elements of the chain, clicked element first */
+ elements: ElementApi[]
+}
+
+export interface ElementStatsResponseApi {
+ /** Element chains with event counts, ordered by count */
+ results: ElementStatsApi[]
+ /**
+ * URL for the next page of results, if any
+ * @nullable
+ */
+ next: string | null
+ /**
+ * URL for the previous page of results, if any
+ * @nullable
+ */
+ previous: string | null
+}
+
export type InsightVizNodeApiKind = (typeof InsightVizNodeApiKind)[keyof typeof InsightVizNodeApiKind]
export const InsightVizNodeApiKind = {
@@ -7763,6 +7792,37 @@ export type ElementsListParams = {
offset?: number
}
+export type ElementsStatsRetrieveParams = {
+ /**
+ * Comma-separated data attribute names (wildcards allowed, e.g. data-*). When provided, each element's attributes map is filtered to matching attr__* keys, shrinking the response.
+ */
+ data_attributes?: string
+ /**
+ * Start of the date range (e.g. -7d, 2024-01-01). Defaults to last 7 days.
+ */
+ date_from?: string
+ /**
+ * End of the date range (e.g. 2024-01-31). Defaults to now.
+ */
+ date_to?: string
+ /**
+ * Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three.
+ */
+ include?: string[]
+ /**
+ * Maximum rows per page
+ */
+ limit?: number
+ /**
+ * Pagination offset
+ */
+ offset?: number
+ /**
+ * Sampling factor between 0 and 1
+ */
+ sampling_factor?: number
+}
+
export type InsightsListParams = {
/**
* Return basic insight metadata only (no results, faster).
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index f7449311992e..b9eb3969c279 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -15,7 +15,9 @@ import type {
ColumnConfigurationApi,
ColumnConfigurationsListParams,
ElementApi,
+ ElementStatsResponseApi,
ElementsListParams,
+ ElementsStatsRetrieveParams,
InsightApi,
InsightViewedRequestApi,
InsightsActivityRetrieveParams,
@@ -273,8 +275,20 @@ export const elementsDestroy = async (projectId: string, id: number, options?: R
})
}
-export const getElementsStatsRetrieveUrl = (projectId: string) => {
- return `/api/projects/${projectId}/elements/stats/`
+export const getElementsStatsRetrieveUrl = (projectId: string, params?: ElementsStatsRetrieveParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/elements/stats/?${stringifiedParams}`
+ : `/api/projects/${projectId}/elements/stats/`
}
/**
@@ -283,8 +297,12 @@ export const getElementsStatsRetrieveUrl = (projectId: string) => {
* Now, you can pass a combination of include query parameters to get different types of elements
* Currently only $autocapture and $rageclick and $dead_click are supported
*/
-export const elementsStatsRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getElementsStatsRetrieveUrl(projectId), {
+export const elementsStatsRetrieve = async (
+ projectId: string,
+ params?: ElementsStatsRetrieveParams,
+ options?: RequestInit
+): Promise<ElementStatsResponseApi> => {
+ return apiMutator<ElementStatsResponseApi>(getElementsStatsRetrieveUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ca9a17f05ef7..403c8ee27805 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18219,6 +18219,35 @@ export namespace Schemas {
order?: number | null;
}
+ export interface ElementStats {
+ /** 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
+ * @nullable
+ */
+ hash: string | null;
+ /** Event type: $autocapture, $rageclick, or $dead_click */
+ type: string;
+ /** Parsed elements of the chain, clicked element first */
+ elements: Element[];
+ }
+
+ export interface ElementStatsResponse {
+ /** Element chains with event counts, ordered by count */
+ results: ElementStats[];
+ /**
+ * URL for the next page of results, if any
+ * @nullable
+ */
+ next: string | null;
+ /**
+ * URL for the previous page of results, if any
+ * @nullable
+ */
+ previous: string | null;
+ }
+
export type ElementTypeAttributes = {[key: string]: string};
export interface ElementType {
@@ -55986,6 +56015,37 @@ export namespace Schemas {
offset?: number;
};
+ export type EnvironmentsElementsStatsRetrieveParams = {
+ /**
+ * Comma-separated data attribute names (wildcards allowed, e.g. data-*). When provided, each element's attributes map is filtered to matching attr__* keys, shrinking the response.
+ */
+ data_attributes?: string;
+ /**
+ * Start of the date range (e.g. -7d, 2024-01-01). Defaults to last 7 days.
+ */
+ date_from?: string;
+ /**
+ * End of the date range (e.g. 2024-01-31). Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three.
+ */
+ include?: string[];
+ /**
+ * Maximum rows per page
+ */
+ limit?: number;
+ /**
+ * Pagination offset
+ */
+ offset?: number;
+ /**
+ * Sampling factor between 0 and 1
+ */
+ sampling_factor?: number;
+ };
+
export type EnvironmentsEndpointsListParams = {
created_by?: number;
is_active?: boolean;
@@ -61952,6 +62012,37 @@ export namespace Schemas {
offset?: number;
};
+ export type ElementsStatsRetrieveParams = {
+ /**
+ * Comma-separated data attribute names (wildcards allowed, e.g. data-*). When provided, each element's attributes map is filtered to matching attr__* keys, shrinking the response.
+ */
+ data_attributes?: string;
+ /**
+ * Start of the date range (e.g. -7d, 2024-01-01). Defaults to last 7 days.
+ */
+ date_from?: string;
+ /**
+ * End of the date range (e.g. 2024-01-31). Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Event types to include: $autocapture, $rageclick, $dead_click. Defaults to all three.
+ */
+ include?: string[];
+ /**
+ * Maximum rows per page
+ */
+ limit?: number;
+ /**
+ * Pagination offset
+ */
+ offset?: number;
+ /**
+ * Sampling factor between 0 and 1
+ */
+ sampling_factor?: number;
+ };
+
export type EndpointsListParams = {
created_by?: number;
is_active?: boolean;