Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(toolbar): key clickmap dedupe on chain content, not the null api hash (#67679)

Paul D'Ambra404997407133
diff --git a/frontend/src/toolbar/TELEMETRY.md b/frontend/src/toolbar/TELEMETRY.md
index b528f2340ee8..8bfa36f431d1 100644
--- a/frontend/src/toolbar/TELEMETRY.md
+++ b/frontend/src/toolbar/TELEMETRY.md
@@ -167,7 +167,7 @@ A user paginating emits one event per page with cumulative `event_count` — gro
| `duration_ms` | `number` | Wall-clock processing time, including main-thread yields; DOM index build time is included only on a cold cache |
| `trigger` | `string` | What started the run: `initial`, `pagination`, `refresh`, or `toggle` |
| `cache_hit` | `boolean` | Whether the page-elements cache was warm (no collect + index rebuild) |
-| `completed` | `boolean` | False when the run was cancelled mid-processing by a newer run |
+| `completed` | `boolean` | False when the run did not finish — superseded by a newer run, or failed mid-processing |
**File:** `elements/heatmapToolbarMenuLogic.ts`
diff --git a/frontend/src/toolbar/elements/domElementIndex.test.ts b/frontend/src/toolbar/elements/domElementIndex.test.ts
index 951b9d28cb9f..305cb1a090d2 100644
--- a/frontend/src/toolbar/elements/domElementIndex.test.ts
+++ b/frontend/src/toolbar/elements/domElementIndex.test.ts
@@ -292,6 +292,48 @@ describe('domElementIndex', () => {
{ tag_name: 'section', attr_class: ['outer-b'] },
],
},
+ {
+ name: 'uses position to pick between siblings sharing a data attribute',
+ html: `
+ <div>
+ <button data-attr="cta"></button>
+ <button data-attr="cta" id="target"></button>
+ </div>
+ `,
+ event: [
+ {
+ tag_name: 'button',
+ attributes: { 'attr__data-attr': 'cta' },
+ nth_child: 2,
+ nth_of_type: 2,
+ },
+ ],
+ dataAttributes: ['data-attr'],
+ },
+ {
+ name: 'ignores drifted sibling position when the clicked element is identified by id',
+ html: `
+ <div class="injected-banner"></div>
+ <button id="target" class="btn"></button>
+ `,
+ event: [{ tag_name: 'button', attr_id: 'target', nth_child: 1, nth_of_type: 1 }],
+ },
+ {
+ name: 'ignores drifted sibling position when the clicked element is identified by a data attribute',
+ html: `
+ <div class="injected-banner"></div>
+ <button data-attr="cta" id="target"></button>
+ `,
+ event: [
+ {
+ tag_name: 'button',
+ attributes: { 'attr__data-attr': 'cta' },
+ nth_child: 1,
+ nth_of_type: 1,
+ },
+ ],
+ dataAttributes: ['data-attr'],
+ },
{
name: 'ignores drifted sibling position when the ancestor is identified by id',
html: `
diff --git a/frontend/src/toolbar/elements/domElementIndex.ts b/frontend/src/toolbar/elements/domElementIndex.ts
index fd38a006c438..7b7de1e7adcf 100644
--- a/frontend/src/toolbar/elements/domElementIndex.ts
+++ b/frontend/src/toolbar/elements/domElementIndex.ts
@@ -89,6 +89,10 @@ function createFingerprint(
}
}
+export function hasNonToolbarShadowRoots(pageElements: HTMLElement[]): boolean {
+ return pageElements.some((el) => !!el.shadowRoot && el.id !== TOOLBAR_ID)
+}
+
export function buildDOMIndex(pageElements: HTMLElement[]): DOMIndex {
const index: DOMIndex = {
byId: new Map(),
@@ -152,27 +156,51 @@ function filterByPosition(candidates: HTMLElement[], eventElement: ElementType,
})
}
+// position disambiguates siblings that share an identifier, but must not exclude a sole
+// candidate (or all candidates) whose sibling position drifted since capture
+function preferPositionMatches(candidates: HTMLElement[], eventElement: ElementType, index: DOMIndex): HTMLElement[] {
+ if (candidates.length <= 1) {
+ return candidates
+ }
+ const positioned = filterByPosition(candidates, eventElement, index)
+ return positioned.length ? positioned : candidates
+}
+
+// derived once per chain level, not per candidate: matchesDataAttribute builds a RegExp per call
+function getMatchedDataAttribute(
+ eventElement: ElementType,
+ dataAttributes: string[]
+): { name: string; value: string } | null {
+ const matchedAttr = matchesDataAttribute(eventElement, dataAttributes)
+ if (!matchedAttr) {
+ return null
+ }
+ const value = eventElement.attributes?.[`attr__${matchedAttr}`]
+ return value === undefined ? null : { name: matchedAttr, value }
+}
+
function getCandidatesFromIndex(
eventElement: ElementType,
dataAttributes: string[],
matchLinksByHref: boolean,
index: DOMIndex
): HTMLElement[] {
- const matchedAttr = matchesDataAttribute(eventElement, dataAttributes)
- if (matchedAttr && eventElement.attributes) {
- const value = eventElement.attributes[`attr__${matchedAttr}`]
- if (value !== undefined) {
- const candidates = index.byDataAttr.get(matchedAttr)?.get(value) || []
- if (candidates.length) {
- return filterByPosition(candidates, eventElement, index)
- }
+ // a configured data attribute or an id identifies the element on its own — mirroring
+ // elementToSelector, which early-returns on these — so sibling-position drift from injected
+ // DOM must not exclude a uniquely identified candidate; position still breaks ties between
+ // siblings that share the identifier
+ const matchedDataAttribute = getMatchedDataAttribute(eventElement, dataAttributes)
+ if (matchedDataAttribute) {
+ const candidates = index.byDataAttr.get(matchedDataAttribute.name)?.get(matchedDataAttribute.value) || []
+ if (candidates.length) {
+ return preferPositionMatches(candidates, eventElement, index)
}
}
if (eventElement.attr_id) {
const candidates = index.byId.get(eventElement.attr_id) || []
if (candidates.length) {
- return filterByPosition(candidates, eventElement, index)
+ return preferPositionMatches(candidates, eventElement, index)
}
}
@@ -195,19 +223,6 @@ function getCandidatesFromIndex(
return filterByPosition(candidates, eventElement, index)
}
-// derived once per chain level, not per candidate: matchesDataAttribute builds a RegExp per call
-function getMatchedDataAttribute(
- eventElement: ElementType,
- dataAttributes: string[]
-): { name: string; value: string } | null {
- const matchedAttr = matchesDataAttribute(eventElement, dataAttributes)
- if (!matchedAttr) {
- return null
- }
- const value = eventElement.attributes?.[`attr__${matchedAttr}`]
- return value === undefined ? null : { name: matchedAttr, value }
-}
-
function fingerprintMatchesEventElement(
fingerprint: ElementFingerprint | undefined,
eventElement: ElementType,
@@ -229,9 +244,10 @@ function fingerprintMatchesEventElement(
}
// an id or configured data attribute identifies the ancestor on its own, so DOM drift that
// shifts sibling positions (cookie banners, injected wrappers) shouldn't kill the match —
- // mirroring elementToSelector, which early-returns on these without position
+ // mirroring elementToSelector, which early-returns on these without position; the id guard
+ // above already established id equality
const identifiedWithoutPosition =
- (!!eventElement.attr_id && fingerprint.id === eventElement.attr_id) ||
+ !!eventElement.attr_id ||
(!!matchedDataAttribute && fingerprint.dataAttrs.get(matchedDataAttribute.name) === matchedDataAttribute.value)
return identifiedWithoutPosition || matchesPosition(fingerprint, eventElement)
}
@@ -306,7 +322,7 @@ export function matchEventToElementUsingSelectors(
dataAttributes: string[],
matchLinksByHref: boolean,
pageElements: HTMLElement[],
- selectorCache: Map<string, HTMLElement[]>,
+ selectorCache: Map<string, HTMLElement[] | null>,
hasShadowRoots: boolean
): CountedHTMLElement | null {
let lastSelector: string | undefined
@@ -318,8 +334,14 @@ export function matchEventToElementUsingSelectors(
elementToSelector(matchLinksByHref ? element : { ...element, href: undefined }, dataAttributes) || '*'
const combinedSelector = lastSelector ? `${selector} > ${lastSelector}` : selector
+ // null marks a selector that previously threw — repeat encounters bail out exactly like
+ // the original failure did
+ let domElements = selectorCache.get(combinedSelector)
+ if (domElements === null) {
+ break
+ }
+
try {
- let domElements: HTMLElement[] | undefined = selectorCache.get(combinedSelector)
if (domElements === undefined) {
domElements = hasShadowRoots
? Array.from(querySelectorAllDeep(combinedSelector, document, pageElements))
@@ -354,12 +376,10 @@ export function matchEventToElementUsingSelectors(
} catch {
// sentinel-cache the failing selector so repeated rows neither re-throw nor re-log,
// and truncate: event-derived selectors can embed long customer-page attribute values
- if (!selectorCache.has(combinedSelector)) {
- selectorCache.set(combinedSelector, [])
- toolbarLogger.warn('heatmap', 'Failed to resolve heatmap element with selector', {
- selector: combinedSelector.slice(0, 200),
- })
- }
+ selectorCache.set(combinedSelector, null)
+ toolbarLogger.warn('heatmap', 'Failed to resolve heatmap element with selector', {
+ selector: combinedSelector.slice(0, 200),
+ })
break
}
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
new file mode 100644
index 000000000000..d0b780f9d877
--- /dev/null
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts
@@ -0,0 +1,45 @@
+import { ElementsEventType } from '~/toolbar/types'
+
+import { dedupeByChainIdentity } from './heatmapToolbarMenuLogic'
+
+function statsRow(overrides: Partial<ElementsEventType>): ElementsEventType {
+ return {
+ count: 1,
+ hash: null,
+ type: '$autocapture',
+ elements: [{ tag_name: 'button', attr_class: ['btn'], nth_child: 1, nth_of_type: 1, attributes: {} }],
+ ...overrides,
+ } as ElementsEventType
+}
+
+describe('dedupeByChainIdentity', () => {
+ const cases = [
+ {
+ name: 'keeps distinct chains even though the API returns hash null for every row',
+ events: [
+ statsRow({ elements: [{ tag_name: 'button', attributes: {} }] as ElementsEventType['elements'] }),
+ statsRow({ elements: [{ tag_name: 'a', attributes: {} }] as ElementsEventType['elements'] }),
+ ],
+ expectedCount: 2,
+ },
+ {
+ name: 'drops a chain repeated across paginated pages, keeping the first occurrence',
+ events: [statsRow({ count: 10 }), statsRow({ count: 3 })],
+ expectedCount: 1,
+ },
+ {
+ name: 'keeps identical chains that differ by event type',
+ events: [statsRow({ type: '$autocapture' }), statsRow({ type: '$rageclick' })],
+ expectedCount: 2,
+ },
+ ]
+
+ it.each(cases)('$name', ({ events, expectedCount }) => {
+ expect(dedupeByChainIdentity(events)).toHaveLength(expectedCount)
+ })
+
+ it('keeps the first occurrence of a duplicated chain', () => {
+ const [kept] = dedupeByChainIdentity([statsRow({ count: 10 }), statsRow({ count: 3 })])
+ expect(kept.count).toBe(10)
+ })
+})
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
index 5728a2ab162b..41dd39d51b24 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
@@ -12,6 +12,7 @@ import { createVersionChecker } from 'lib/utils/semver'
import {
DOMIndex,
buildDOMIndex,
+ hasNonToolbarShadowRoots,
matchEventToElementUsingIndex,
matchEventToElementUsingSelectors,
} from '~/toolbar/elements/domElementIndex'
@@ -20,14 +21,14 @@ import { toolbarApi } from '~/toolbar/toolbarApi'
import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'
-import { TOOLBAR_ID, elementIsVisible, invalidateZoomCache, trimElement } from '~/toolbar/utils'
+import { elementIsVisible, invalidateZoomCache, trimElement } from '~/toolbar/utils'
import { PropertyFilterType, PropertyOperator } from '~/types'
import type { heatmapToolbarMenuLogicType } from './heatmapToolbarMenuLogicType'
export const doesVersionSupportScrollDepth = createVersionChecker('1.99')
-export const ELEMENT_STATS_PAGE_LIMIT = 5000
+const ELEMENT_STATS_PAGE_LIMIT = 5000
function yieldToMain(): Promise<void> {
return new Promise((resolve) => {
@@ -46,7 +47,7 @@ export type ClickmapProcessingTrigger = 'initial' | 'pagination' | 'refresh' | '
interface ElementProcessingCache {
pageElements?: HTMLElement[]
domIndex?: DOMIndex
- selectorToElements: Map<string, HTMLElement[]>
+ selectorToElements: Map<string, HTMLElement[] | null>
lastHref?: string
intersectionObserver?: IntersectionObserver
visibilityCache: WeakMap<HTMLElement, boolean>
@@ -68,13 +69,16 @@ function getCachedPageElements(
const cacheValid = cache.pageElements && !hrefChanged && !cache.cacheInvalidated
if (cacheValid && cache.pageElements && cache.domIndex) {
- return {
- pageElements: cache.pageElements,
- domIndex: cache.domIndex,
- // attachShadow() emits no light-DOM mutation, so the build-time flag can go stale —
- // recheck the snapshot on every run
- hasShadowRoots: cache.pageElements.some((el) => el.shadowRoot && el.id !== TOOLBAR_ID),
- cacheHit: true,
+ // attachShadow() emits no light-DOM mutation, so shadow roots can appear without
+ // invalidating the cache; when that happens the snapshot predates the shadow content,
+ // so rebuild rather than just flipping the flag over stale data
+ if (hasNonToolbarShadowRoots(cache.pageElements) === cache.domIndex.hasShadowRoots) {
+ return {
+ pageElements: cache.pageElements,
+ domIndex: cache.domIndex,
+ hasShadowRoots: cache.domIndex.hasShadowRoots,
+ cacheHit: true,
+ }
}
}
@@ -301,11 +305,13 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
}
return {
- results: dedupeByChainIdentity([
- // if url is present we are paginating and merge results, otherwise we only use the new results
- ...(url ? values.elementStats?.results || [] : []),
- ...(result.data.results || []),
- ]),
+ // if url is present we are paginating and merge results, otherwise we only use the new results
+ results: url
+ ? dedupeByChainIdentity([
+ ...(values.elementStats?.results || []),
+ ...(result.data.results || []),
+ ])
+ : result.data.results || [],
next: result.data.next,
previous: result.data.previous,
} as PaginatedResponse<ElementsEventType>
@@ -324,6 +330,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
},
],
elementCount: [(s) => [s.countedElements], (countedElements) => countedElements.length],
+ loadedElementStatsCount: [(s) => [s.elementStats], (elementStats) => elementStats?.results?.length ?? 0],
clickCount: [
(s) => [s.countedElements],
(countedElements) => (countedElements ? countedElements.map((e) => e.count).reduce((a, b) => a + b, 0) : 0),
@@ -650,11 +657,13 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
}),
])
-function dedupeByChainIdentity(events: ElementsEventType[]): ElementsEventType[] {
+export function dedupeByChainIdentity(events: ElementsEventType[]): ElementsEventType[] {
const seen = new Set<string>()
const deduped: ElementsEventType[] = []
for (const event of events) {
- const identity = `${event.type}:${event.hash}`
+ // /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)}`
if (seen.has(identity)) {
continue
}
diff --git a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx
index 8a605979aa85..c1a808291849 100644
--- a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx
+++ b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx
@@ -18,7 +18,7 @@ import { urls } from 'scenes/urls'
import { ToolbarMenu } from '~/toolbar/bar/ToolbarMenu'
import { elementsLogic } from '~/toolbar/elements/elementsLogic'
-import { ELEMENT_STATS_PAGE_LIMIT, heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'
+import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'
import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'
import { joinWithUiHost } from '~/toolbar/utils'
@@ -91,6 +91,7 @@ export const HeatmapToolbarMenu = (): JSX.Element => {
commonFilters,
heatmapFilters,
canLoadMoreElementStats,
+ loadedElementStatsCount,
viewportRange,
rawHeatmapLoading,
elementStatsLoading,
@@ -310,9 +311,9 @@ export const HeatmapToolbarMenu = (): JSX.Element => {
'!'
)}
</div>
- {canLoadMoreElementStats && (
+ {canLoadMoreElementStats && loadedElementStatsCount > 0 && (
<div className="mb-2 text-muted text-xs">
- Showing the top {ELEMENT_STATS_PAGE_LIMIT.toLocaleString()} element groups by click
+ Showing the top {loadedElementStatsCount.toLocaleString()} element groups by click
count — load more for the full data range.
</div>
)}
diff --git a/frontend/src/toolbar/types.ts b/frontend/src/toolbar/types.ts
index f683061e6080..31a7fd348652 100644
--- a/frontend/src/toolbar/types.ts
+++ b/frontend/src/toolbar/types.ts
@@ -5,7 +5,7 @@ import { FragileSelectorResult } from './utils/selectorQuality'
export type ElementsEventType = {
count: number
elements: ElementType[]
- hash: string
+ hash: string | null
type: '$autocapture' | '$rageclick'
}
@@ -38,7 +38,7 @@ export interface CountedHTMLElement {
rageclickCount: number
deadclickCount: number
element: HTMLElement
- hash: string
+ hash: string | null
selector: string
position?: number
actionStep?: ActionStepType