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(web-analytics): apply path cleaning to the live top pages panel (#87140)

Lucas Ricoy376a379bb57c
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx
index 2dfc0e2175ab..8fe47edcdb30 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx
@@ -30,6 +30,7 @@ import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'
import { LiveEventsFeed, LiveEventsFeedColumn } from 'scenes/activity/live/LiveEventsFeed'
import { teamLogic } from 'scenes/teamLogic'
+import { PathCleaningToggle } from '../PathCleaningToggle'
import { LIVE_STREAM_OPERATORS, isLiveStreamFilter, webAnalyticsFilterLogic } from '../webAnalyticsFilterLogic'
import { WebAnalyticsDomainSelector, WebAnalyticsLiveDeviceToggle } from '../WebAnalyticsFilters'
import { webAnalyticsLogic } from '../webAnalyticsLogic'
@@ -94,8 +95,9 @@ const LiveDashboardFilterRow = ({
setEditing: (isEditing: boolean) => void
}): JSX.Element => {
const [displayFilters, setDisplayFilters] = useState(false)
- const { rawWebAnalyticsFilters, deviceTypeFilter, validatedDomainFilter } = useValues(webAnalyticsLogic)
- const { setDeviceTypeFilter, setWebAnalyticsFilters } = useActions(webAnalyticsLogic)
+ const { rawWebAnalyticsFilters, deviceTypeFilter, validatedDomainFilter, isPathCleaningEnabled } =
+ useValues(webAnalyticsLogic)
+ const { setDeviceTypeFilter, setWebAnalyticsFilters, setIsPathCleaningEnabled } = useActions(webAnalyticsLogic)
const { clearFilters } = useActions(webAnalyticsFilterLogic)
const { isRefreshing } = useValues(liveWebAnalyticsMetricsLogic)
@@ -213,6 +215,7 @@ const LiveDashboardFilterRow = ({
Filters
</LemonButton>
</Popover>
+ <PathCleaningToggle value={isPathCleaningEnabled} onChange={setIsPathCleaningEnabled} />
<WebAnalyticsDomainSelector />
</>
}
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.test.ts b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.test.ts
new file mode 100644
index 000000000000..ecae7efb0fcb
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.test.ts
@@ -0,0 +1,89 @@
+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_PROJECT, MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import api from 'lib/api'
+import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
+
+import { initKeaTests } from '~/test/init'
+import { AvailableFeature, LiveEvent } from '~/types'
+
+import { liveWebAnalyticsMetricsLogic } from './liveWebAnalyticsMetricsLogic'
+
+const CLASSES_RULE = { alias: '/classes/:id', regex: '/classes/[^/]+', order: 0 }
+
+const pageview = (pathname: string, distinctId: string): LiveEvent => ({
+ uuid: `${distinctId}-${pathname}`,
+ event: '$pageview',
+ properties: { $pathname: pathname, $device_id: distinctId },
+ timestamp: new Date().toISOString(),
+ team_id: MOCK_DEFAULT_TEAM.id,
+ distinct_id: distinctId,
+ created_at: new Date().toISOString(),
+})
+
+describe('liveWebAnalyticsMetricsLogic', () => {
+ let logic: ReturnType<typeof liveWebAnalyticsMetricsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, path_cleaning_filters: [CLASSES_RULE] }, MOCK_DEFAULT_PROJECT, {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ available_product_features: [
+ { key: AvailableFeature.PATHS_ADVANCED, name: AvailableFeature.PATHS_ADVANCED },
+ ],
+ })
+ jest.spyOn(api, 'query').mockResolvedValue({ results: [] } as any)
+ ;(posthog as any).setPersonProperties = jest.fn()
+ logic = liveWebAnalyticsMetricsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it('collapses streamed pageviews that clean to the same path into one row', () => {
+ logic.actions.addEvents(
+ [pageview('/classes/928q3hr9paw8hfe', 'user-1'), pageview('/classes/j2k4l6m8n0p', 'user-2')],
+ new Date(Date.now() - 60_000),
+ logic.values.pathCleaningFilters
+ )
+
+ expect(logic.values.topPaths).toEqual([{ path: '/classes/:id', views: 2 }])
+ })
+
+ it('leaves streamed paths untouched once path cleaning is switched off', () => {
+ webAnalyticsLogic.actions.setIsPathCleaningEnabled(false)
+
+ logic.actions.addEvents(
+ [pageview('/classes/928q3hr9paw8hfe', 'user-1')],
+ new Date(Date.now() - 60_000),
+ logic.values.pathCleaningFilters
+ )
+
+ expect(logic.values.topPaths).toEqual([{ path: '/classes/928q3hr9paw8hfe', views: 1 }])
+ })
+
+ it('queues a reload for a path cleaning change that lands during the initial load', async () => {
+ // Rebuild the logic against a gated query mock so the initial load stays in flight.
+ logic.unmount()
+ let openGate: () => void = () => {}
+ const gate = new Promise<void>((resolve) => {
+ openGate = resolve
+ })
+ jest.spyOn(api, 'query').mockImplementation(async () => {
+ await gate
+ return { results: [] } as any
+ })
+ logic = liveWebAnalyticsMetricsLogic()
+ logic.mount()
+
+ // The in-flight load captured the old setting; this change must not be dropped.
+ webAnalyticsLogic.actions.setIsPathCleaningEnabled(!webAnalyticsLogic.values.isPathCleaningEnabled)
+ openGate()
+
+ await expectLogic(logic).toDispatchActions(['scheduleReload', 'loadInitialData'])
+ })
+})
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
index 4e4aa63aa8b9..4a47338aa6e0 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
@@ -5,6 +5,7 @@ import { subscriptions } from 'kea-subscriptions'
import { lemonToast } from '@posthog/lemon-ui'
import { createStreamConnection } from 'lib/api-stream'
+import { applyPathCleaning } from 'lib/components/PathCleanFilters/pathCleaningUtils'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -31,7 +32,7 @@ import {
TrendsQueryResponse,
WebAnalyticsPropertyFilter,
} from '~/queries/schema/schema-general'
-import { AnyPropertyFilter, BaseMathType, LiveEvent, PropertyOperator } from '~/types'
+import { AnyPropertyFilter, BaseMathType, LiveEvent, PathCleaningFilter, PropertyOperator } from '~/types'
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { TeamPublicType, TeamType } from '../../../types'
@@ -129,6 +130,7 @@ export interface liveWebAnalyticsMetricsLogicValues {
rawLiveFilters: WebAnalyticsPropertyFilter[] // webAnalyticsFilterLogic
rawLiveStreamFilters: WebAnalyticsPropertyFilter[] // webAnalyticsFilterLogic
rawSelectedHost: string | null // webAnalyticsFilterLogic
+ isPathCleaningEnabled: boolean // webAnalyticsLogic
productTab: ProductTab // webAnalyticsLogic
shouldFilterTestAccounts: boolean // webAnalyticsLogic
botBreakdown: BotBreakdownItem[]
@@ -144,6 +146,7 @@ export interface liveWebAnalyticsMetricsLogicValues {
isRefreshing: boolean
liveFilters: WebAnalyticsPropertyFilter[]
liveUserCount: number
+ pathCleaningFilters: PathCleaningFilter[]
recentEvents: LiveEvent[]
recentUsersByLastSeen: Map<string, number>
selectedHost: string | null
@@ -166,10 +169,12 @@ export interface liveWebAnalyticsMetricsLogicValues {
export interface liveWebAnalyticsMetricsLogicActions {
addEvents: (
events: LiveEvent[],
- newerThan: Date
+ newerThan: Date,
+ pathCleaningFilters?: PathCleaningFilter[]
) => {
events: LiveEvent[]
newerThan: Date
+ pathCleaningFilters: PathCleaningFilter[]
}
addGeoEvents: (events: LiveGeoEvent[]) => {
events: LiveGeoEvent[]
@@ -246,6 +251,10 @@ export interface liveWebAnalyticsMetricsLogicMeta {
liveUserCount: (recentUsersByLastSeen: Map<string, number>) => number
selectedHost: (rawSelectedHost: string | null, productTab: ProductTab) => string | null
liveFilters: (rawLiveFilters: WebAnalyticsPropertyFilter[]) => WebAnalyticsPropertyFilter[]
+ pathCleaningFilters: (
+ currentTeam: TeamPublicType | TeamType | null,
+ isPathCleaningEnabled: boolean
+ ) => PathCleaningFilter[]
testAccountFilters: (
currentTeam: TeamPublicType | TeamType | null,
shouldFilterTestAccounts: boolean
@@ -281,11 +290,15 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
'liveStreamFilters as rawLiveStreamFilters',
],
webAnalyticsLogic,
- ['productTab', 'shouldFilterTestAccounts'],
+ ['productTab', 'shouldFilterTestAccounts', 'isPathCleaningEnabled'],
],
})),
actions(() => ({
- addEvents: (events: LiveEvent[], newerThan: Date) => ({ events, newerThan }),
+ addEvents: (events: LiveEvent[], newerThan: Date, pathCleaningFilters: PathCleaningFilter[] = []) => ({
+ events,
+ newerThan,
+ pathCleaningFilters,
+ }),
addGeoEvents: (events: LiveGeoEvent[]) => ({ events }),
setInitialData: (
buckets: { timestamp: number; bucket: SlidingWindowBucket }[],
@@ -316,13 +329,19 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
freshWindow.prune()
return freshWindow
},
- addEvents: (window, { events, newerThan }) => {
+ addEvents: (window, { events, newerThan, pathCleaningFilters }) => {
for (const event of events) {
const eventTs = new Date(event.timestamp).getTime() / 1000
const newerThanTs = newerThan.getTime() / 1000
if (eventTs > newerThanTs) {
- const pathname = event.properties?.$pathname
+ // Streamed events arrive raw, so the same cleaning the backfill query
+ // does server-side has to happen here for both to land on one key.
+ const rawPathname = event.properties?.$pathname
+ const pathname =
+ typeof rawPathname === 'string'
+ ? applyPathCleaning(rawPathname, pathCleaningFilters)
+ : rawPathname
const deviceType = event.properties?.$device_type
const deviceId = event.properties?.$device_id
const browser = event.properties?.$browser
@@ -575,6 +594,16 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
(s) => [s.rawLiveFilters],
(rawLiveFilters: WebAnalyticsPropertyFilter[]): WebAnalyticsPropertyFilter[] => rawLiveFilters,
],
+ pathCleaningFilters: [
+ (s) => [s.currentTeam, s.isPathCleaningEnabled],
+ (currentTeam: TeamPublicType | TeamType | null, isPathCleaningEnabled: boolean): PathCleaningFilter[] => {
+ if (!isPathCleaningEnabled || !currentTeam || !('path_cleaning_filters' in currentTeam)) {
+ return []
+ }
+ return currentTeam.path_cleaning_filters ?? []
+ },
+ { resultEqualityCheck: equal },
+ ],
testAccountFilters: [
(s) => [s.currentTeam, s.shouldFilterTestAccounts],
(currentTeam: TeamPublicType | TeamType | null, shouldFilterTestAccounts: boolean): AnyPropertyFilter[] =>
@@ -663,6 +692,7 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
filterTestAccounts: values.shouldFilterTestAccounts,
includeCity: !!values.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_LIVE_CITY_BREAKDOWN],
filtersEnabled: true,
+ doPathCleaning: values.pathCleaningFilters.length > 0,
abortController,
})
@@ -711,6 +741,12 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
actions.setIsRefreshing(false)
}
cache.hasInitialized = true
+ // A filter change that arrived mid-load was queued rather than dropped:
+ // this load captured the old filters, so run one more with the new ones.
+ if (!signal.aborted && cache.reloadQueuedDuringInit) {
+ cache.reloadQueuedDuringInit = false
+ resetStreamStateAndReload(cache as FlushCache, actions)
+ }
}
},
scheduleReload: async (_, breakpoint) => {
@@ -812,23 +848,23 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
subscriptions(({ actions, cache }) => {
const reloadForFilterChange = (): void => {
if (!cache.hasInitialized) {
+ cache.reloadQueuedDuringInit = true
return
}
- cache.batch = []
- cache.geoBatch = []
- actions.clearRecentEvents()
- actions.clearFilteredLiveUsers()
- actions.scheduleReload()
+ resetStreamStateAndReload(cache as FlushCache, actions)
}
return {
liveFilters: reloadForFilterChange,
shouldFilterTestAccounts: reloadForFilterChange,
+ // The window holds already-cleaned paths, so new rules only apply once it's rebuilt.
+ pathCleaningFilters: reloadForFilterChange,
}
}),
- events(({ actions, cache }) => ({
+ events(({ actions, values, cache }) => ({
afterMount: () => {
cache.batch = [] as LiveEvent[]
cache.geoBatch = [] as LiveGeoEvent[]
+ cache.getPathCleaningFilters = () => values.pathCleaningFilters
actions.loadInitialData()
startFlushInterval(cache as FlushCache, actions as FlushActions)
@@ -863,11 +899,13 @@ interface FlushCache {
batch: LiveEvent[]
geoBatch: LiveGeoEvent[]
newerThan: Date
+ // Read at flush time rather than captured, so a rule change reaches the next batch.
+ getPathCleaningFilters: () => PathCleaningFilter[]
disposables: DisposablesManager
}
interface FlushActions {
- addEvents: (events: LiveEvent[], newerThan: Date) => void
+ addEvents: (events: LiveEvent[], newerThan: Date, pathCleaningFilters: PathCleaningFilter[]) => void
addGeoEvents: (events: LiveGeoEvent[]) => void
tickLiveUserCount: () => void
}
@@ -876,6 +914,22 @@ const stopFlushInterval = (cache: FlushCache): void => {
cache.disposables.dispose('flushInterval')
}
+interface ReloadActions {
+ clearRecentEvents: () => void
+ clearFilteredLiveUsers: () => void
+ scheduleReload: () => void
+}
+
+// Drops buffered stream state and schedules a fresh backfill; the window is
+// rebuilt from scratch whenever the filters feeding it change.
+const resetStreamStateAndReload = (cache: Pick<FlushCache, 'batch' | 'geoBatch'>, actions: ReloadActions): void => {
+ cache.batch = []
+ cache.geoBatch = []
+ actions.clearRecentEvents()
+ actions.clearFilteredLiveUsers()
+ actions.scheduleReload()
+}
+
// Drives the "Users online" count so users drop off within ~5s of leaving the 60s window
const startLiveUserCountInterval = (cache: FlushCache, actions: FlushActions): void => {
cache.disposables.add(() => {
@@ -916,7 +970,7 @@ const startFlushInterval = (cache: FlushCache, actions: FlushActions): void => {
cache.disposables.add(() => {
const intervalId = setInterval(() => {
if (cache.batch.length > 0) {
- actions.addEvents(cache.batch, cache.newerThan)
+ actions.addEvents(cache.batch, cache.newerThan, cache.getPathCleaningFilters())
cache.batch = []
}
if (cache.geoBatch.length > 0) {
@@ -963,6 +1017,7 @@ const loadQueryData = async ({
filterTestAccounts,
includeCity,
filtersEnabled,
+ doPathCleaning,
abortController,
}: {
dateFrom: Date
@@ -971,6 +1026,7 @@ const loadQueryData = async ({
filterTestAccounts: boolean
includeCity: boolean
filtersEnabled: boolean
+ doPathCleaning: boolean
abortController: AbortController
}): Promise<LiveQueryData> => {
const { signal } = abortController
@@ -1057,6 +1113,9 @@ const loadQueryData = async ({
breakdown: '$pathname',
breakdown_limit: 10,
breakdown_hide_other_aggregation: true,
+ // Cleaning runs before the breakdown is ranked, so a path that only reaches the top
+ // once its ids collapse still makes the list.
+ breakdown_path_cleaning: doPathCleaning,
},
dateRange: {
date_from: dateFrom.toISOString(),