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.

refactor(analytics): split sanitizeQuery and dashboard view properties (#99217)

Paul D'Ambracc4d409c7e64
diff --git a/frontend/src/lib/utils/eventUsageLogic.test.ts b/frontend/src/lib/utils/eventUsageLogic.test.ts
index 164d81036f73..8ad294019f54 100644
--- a/frontend/src/lib/utils/eventUsageLogic.test.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.test.ts
@@ -13,10 +13,22 @@ import type {
Node,
} from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { BaseMathType, BehavioralEventType, FilterLogicalOperator, PropertyFilterType } from '~/types'
+import {
+ BaseMathType,
+ BehavioralEventType,
+ ChartDisplayType,
+ type DashboardTile,
+ type DashboardType,
+ FilterLogicalOperator,
+ FunnelVizType,
+ PropertyFilterType,
+ type QueryBasedInsightModel,
+ StepOrderValue,
+} from '~/types'
import {
type OnboardingEventProperties,
+ dashboardViewedProperties,
eventUsageLogic,
getEventPropertiesForMetric,
sanitizeQuery,
@@ -298,6 +310,166 @@ describe('eventUsageLogic', () => {
expect(sanitizeQuery(query).behavioral_filter_count).toBe(2)
})
+
+ const trendsSource = {
+ kind: NodeKind.TrendsQuery,
+ dateRange: { date_from: '-7d', date_to: null },
+ interval: 'day',
+ samplingFactor: 0.1,
+ filterTestAccounts: true,
+ series: [
+ { kind: NodeKind.EventsNode, event: '$pageview' },
+ { kind: NodeKind.ActionsNode, id: 1 },
+ { kind: NodeKind.DataWarehouseNode, table_name: 'orders' },
+ ],
+ breakdownFilter: { breakdown_type: 'event', breakdown_limit: 5, breakdown_hide_other_aggregation: true },
+ compareFilter: { compare: true, compare_to: '-1w' },
+ trendsFilter: { formula: 'A + B' },
+ }
+ const trendsProperties = {
+ uses_data_warehouse_source: true,
+ date_from: '-7d',
+ interval: 'day',
+ samplingFactor: 0.1,
+ series_length: 3,
+ event_entity_count: 1,
+ action_entity_count: 1,
+ data_warehouse_entity_count: 1,
+ has_properties: false,
+ behavioral_filter_count: 0,
+ filter_test_accounts: true,
+ breakdown_type: 'event',
+ breakdown_limit: 5,
+ breakdown_hide_other_aggregation: true,
+ has_formula: true,
+ display: ChartDisplayType.ActionsLineGraph,
+ compare: true,
+ compare_to: '-1w',
+ }
+ const funnelsSource = {
+ kind: NodeKind.FunnelsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ funnelsFilter: { funnelVizType: FunnelVizType.Steps, funnelOrderType: StepOrderValue.STRICT },
+ }
+
+ const cases: [string, unknown, Record<string, unknown>][] = [
+ ['null', null, { uses_data_warehouse_source: false }],
+ [
+ 'a trends query wrapped in an InsightVizNode',
+ { kind: NodeKind.InsightVizNode, source: trendsSource },
+ { query_kind: NodeKind.InsightVizNode, query_source_kind: NodeKind.TrendsQuery, ...trendsProperties },
+ ],
+ ['a bare trends query', trendsSource, { query_kind: NodeKind.TrendsQuery, ...trendsProperties }],
+ [
+ 'a funnels query',
+ funnelsSource,
+ {
+ query_kind: NodeKind.FunnelsQuery,
+ uses_data_warehouse_source: false,
+ series_length: 1,
+ event_entity_count: 1,
+ action_entity_count: 0,
+ data_warehouse_entity_count: 0,
+ has_properties: false,
+ behavioral_filter_count: 0,
+ has_formula: false,
+ funnel_viz_type: FunnelVizType.Steps,
+ funnel_order_type: StepOrderValue.STRICT,
+ },
+ ],
+ [
+ 'a non-insight query',
+ { kind: NodeKind.DataTableNode, source: { kind: NodeKind.HogQLQuery, query: 'select 1' } },
+ {
+ query_kind: NodeKind.DataTableNode,
+ query_source_kind: NodeKind.HogQLQuery,
+ uses_data_warehouse_source: false,
+ },
+ ],
+ ]
+
+ it.each(cases)('describes %s without its filter values', (_, query, expected) => {
+ expect(sanitizeQuery(query as Node | null)).toEqual(expected)
+ })
+ })
+
+ describe('dashboardViewedProperties', () => {
+ const dashboard = (
+ tiles: Partial<DashboardTile<QueryBasedInsightModel>>[]
+ ): DashboardType<QueryBasedInsightModel> =>
+ ({
+ id: 7,
+ created_at: '2026-01-01T00:00:00Z',
+ is_shared: false,
+ pinned: true,
+ creation_mode: 'default',
+ created_by: { uuid: 'creator' },
+ tiles,
+ }) as unknown as DashboardType<QueryBasedInsightModel>
+
+ const insightTile = (query: unknown, is_sample = false): Partial<DashboardTile<QueryBasedInsightModel>> =>
+ ({ insight: { query, is_sample } }) as unknown as Partial<DashboardTile<QueryBasedInsightModel>>
+
+ const cases: [string, Partial<DashboardTile<QueryBasedInsightModel>>[], Record<string, unknown>][] = [
+ ['no tiles', [], { item_count: 0, sample_items_count: 0 }],
+ [
+ 'an insight tile with a query',
+ [insightTile({ kind: NodeKind.InsightVizNode, source: { kind: NodeKind.TrendsQuery, series: [] } })],
+ { item_count: 1, text_count: 1, uses_data_warehouse_source: false, data_warehouse_tiles_count: 0 },
+ ],
+ ['an insight tile without a query', [insightTile(null)], { item_count: 1, empty_count: 1 }],
+ [
+ 'a sample insight tile that reads the warehouse',
+ [insightTile({ kind: NodeKind.TrendsQuery, series: [{ kind: NodeKind.DataWarehouseNode }] }, true)],
+ {
+ item_count: 1,
+ text_count: 1,
+ sample_items_count: 1,
+ uses_data_warehouse_source: true,
+ data_warehouse_tiles_count: 1,
+ },
+ ],
+ [
+ 'text and widget tiles',
+ [{ text: { body: 'hi' } }, { text: { body: 'there' } }, { widget: {} }] as Partial<
+ DashboardTile<QueryBasedInsightModel>
+ >[],
+ { item_count: 3, text_tiles_count: 2, widget_tiles_count: 1 },
+ ],
+ ]
+
+ it.each(cases)('counts %s', (_, tiles, expected) => {
+ expect(dashboardViewedProperties(dashboard(tiles), null, 'viewer')).toEqual({
+ created_at: '2026-01-01T00:00:00Z',
+ is_shared: false,
+ pinned: true,
+ creation_mode: 'default',
+ viewer_is_creator: false,
+ created_by_system: false,
+ dashboard_id: 7,
+ lastRefreshed: undefined,
+ refreshAge: undefined,
+ sample_items_count: 0,
+ uses_data_warehouse_source: false,
+ data_warehouse_tiles_count: 0,
+ ...expected,
+ })
+ })
+
+ const viewerCases: [string, { uuid: string } | null, string | undefined, boolean | undefined][] = [
+ ['the creator views it', { uuid: 'creator' }, 'creator', true],
+ ['another user views it', { uuid: 'creator' }, 'viewer', false],
+ ['the viewer is unknown', { uuid: 'creator' }, undefined, undefined],
+ ['the system created it', null, 'viewer', undefined],
+ ]
+
+ it.each(viewerCases)('reports viewer_is_creator when %s', (_, created_by, viewerUuid, expected) => {
+ const withCreator = { ...dashboard([]), created_by } as unknown as DashboardType<QueryBasedInsightModel>
+ expect(dashboardViewedProperties(withCreator, null, viewerUuid)).toMatchObject({
+ viewer_is_creator: expected,
+ created_by_system: created_by === null,
+ })
+ })
})
describe('legacy formats', () => {
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 5415c419df13..f56cac8a0461 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -22,6 +22,7 @@ import {
ExperimentMetricSource,
ExperimentRetentionMetric,
ExperimentTrendsQuery,
+ InsightQueryNode,
isExperimentFunnelMetric,
isExperimentMeanMetric,
isExperimentRatioMetric,
@@ -507,57 +508,139 @@ function countBehavioralFilters(value: unknown): number {
)
}
-/** Takes a query and returns an object with "useful" properties that don't contain sensitive data. */
-export function sanitizeQuery(query: Node | null): Record<string, string | number | boolean | undefined> {
- const payload: Record<string, string | number | boolean | undefined> = {
- query_kind: query?.kind,
- query_source_kind: isNodeWithSource(query) ? query.source.kind : undefined,
- // Whether this insight/query reads from a connector-synced data warehouse source (series-level
- // detection). Raw SQL/HogQL warehouse usage is flagged from the query response in performQuery.
- uses_data_warehouse_source: queryUsesDataWarehouse(query),
+type SanitizedQuery = Record<string, string | number | boolean | undefined>
+
+function insightQuerySource(query: Node | null): InsightQueryNode | undefined {
+ if (isInsightVizNode(query)) {
+ return query.source
}
+ return isInsightQueryNode(query) ? query : undefined
+}
- if (isInsightVizNode(query) || isInsightQueryNode(query)) {
- const querySource = isInsightVizNode(query) ? query.source : query
- const { dateRange, filterTestAccounts, properties } = querySource
- const samplingFactor = 'samplingFactor' in querySource ? querySource.samplingFactor : undefined
+function dateRangeAndSamplingProperties(querySource: InsightQueryNode): SanitizedQuery {
+ return {
+ date_from: querySource.dateRange?.date_from || undefined,
+ date_to: querySource.dateRange?.date_to || undefined,
+ interval: getInterval(querySource),
+ samplingFactor: ('samplingFactor' in querySource ? querySource.samplingFactor : undefined) || undefined,
+ }
+}
+
+function seriesProperties(querySource: InsightQueryNode): SanitizedQuery {
+ const series = getSeries(querySource)
+ return {
+ series_length: series?.length,
+ event_entity_count: series?.filter((e) => isEventsNode(e)).length,
+ action_entity_count: series?.filter((e) => isActionsNode(e)).length,
+ data_warehouse_entity_count: series?.filter((e) => isAnyDataWarehouseNode(e)).length,
+ has_properties: !!querySource.properties,
+ behavioral_filter_count: countBehavioralFilters(querySource),
+ filter_test_accounts: querySource.filterTestAccounts,
+ }
+}
+
+function breakdownProperties(querySource: InsightQueryNode): SanitizedQuery {
+ const breakdown = getBreakdown(querySource)
+ return {
+ breakdown_type: breakdown?.breakdown_type || undefined,
+ breakdown_limit: breakdown?.breakdown_limit || undefined,
+ breakdown_hide_other_aggregation: breakdown?.breakdown_hide_other_aggregation || undefined,
+ }
+}
+
+function trendsLikeProperties(querySource: InsightQueryNode): SanitizedQuery {
+ const defaultDisplay =
+ isTrendsQuery(querySource) || isStickinessQuery(querySource) ? ChartDisplayType.ActionsLineGraph : undefined
+ return {
+ has_formula: !!getFormula(querySource),
+ display: getDisplay(querySource) ?? defaultDisplay,
+ compare: getCompareFilter(querySource)?.compare,
+ compare_to: getCompareFilter(querySource)?.compare_to,
+ }
+}
+
+function funnelProperties(querySource: InsightQueryNode): SanitizedQuery {
+ if (!isFunnelsQuery(querySource)) {
+ return {}
+ }
+ return {
+ funnel_viz_type: querySource.funnelsFilter?.funnelVizType,
+ funnel_order_type: querySource.funnelsFilter?.funnelOrderType,
+ }
+}
- // date range and sampling
- payload.date_from = dateRange?.date_from || undefined
- payload.date_to = dateRange?.date_to || undefined
- payload.interval = getInterval(querySource)
- payload.samplingFactor = samplingFactor || undefined
+function increment(counts: Record<string, any>, key: string): void {
+ counts[key] = (counts[key] || 0) + 1
+}
- // series
- payload.series_length = getSeries(querySource)?.length
- payload.event_entity_count = getSeries(querySource)?.filter((e) => isEventsNode(e)).length
- payload.action_entity_count = getSeries(querySource)?.filter((e) => isActionsNode(e)).length
- payload.data_warehouse_entity_count = getSeries(querySource)?.filter((e) => isAnyDataWarehouseNode(e)).length
+function insightTileCountKey(tile: DashboardTile<QueryBasedInsightModel>): string {
+ const query = isNodeWithSource(tile.insight?.query) ? tile.insight.query.source : tile.insight?.query
+ return `${query?.kind || !!tile.text ? 'text' : 'empty'}_count`
+}
- // properties
- payload.has_properties = !!properties
- payload.behavioral_filter_count = countBehavioralFilters(querySource)
- payload.filter_test_accounts = filterTestAccounts
+function countDashboardTiles(tiles: DashboardTile<QueryBasedInsightModel>[], properties: Record<string, any>): void {
+ for (const tile of tiles) {
+ if (tile.insight) {
+ increment(properties, insightTileCountKey(tile))
+ properties.sample_items_count += tile.insight.is_sample ? 1 : 0
+ if (queryUsesDataWarehouse(tile.insight.query)) {
+ properties.uses_data_warehouse_source = true
+ properties.data_warehouse_tiles_count += 1
+ }
+ } else if (tile.widget) {
+ increment(properties, 'widget_tiles_count')
+ } else {
+ increment(properties, 'text_tiles_count')
+ }
+ }
+}
- // breakdown
- payload.breakdown_type = getBreakdown(querySource)?.breakdown_type || undefined
- payload.breakdown_limit = getBreakdown(querySource)?.breakdown_limit || undefined
- payload.breakdown_hide_other_aggregation =
- getBreakdown(querySource)?.breakdown_hide_other_aggregation || undefined
+export function dashboardViewedProperties(
+ dashboard: DashboardType<QueryBasedInsightModel>,
+ lastRefreshed: Dayjs | null,
+ viewerUuid: string | undefined
+): Record<string, any> {
+ const { created_at, is_shared, pinned, creation_mode, id } = dashboard
+ const properties: Record<string, any> = {
+ created_at,
+ is_shared,
+ pinned,
+ creation_mode,
+ viewer_is_creator:
+ dashboard.created_by?.uuid && viewerUuid ? dashboard.created_by.uuid === viewerUuid : undefined,
+ sample_items_count: 0,
+ item_count: dashboard.tiles?.length || 0,
+ created_by_system: !dashboard.created_by,
+ dashboard_id: id,
+ lastRefreshed: lastRefreshed?.toISOString(),
+ refreshAge: lastRefreshed ? now().diff(lastRefreshed, 'seconds') : undefined,
+ uses_data_warehouse_source: false,
+ data_warehouse_tiles_count: 0,
+ }
+ countDashboardTiles(dashboard.tiles || [], properties)
+ return properties
+}
- // trends like
- payload.has_formula = !!getFormula(querySource)
- payload.display =
- getDisplay(querySource) ??
- (isTrendsQuery(querySource) || isStickinessQuery(querySource)
- ? ChartDisplayType.ActionsLineGraph
- : undefined)
- payload.compare = getCompareFilter(querySource)?.compare
- payload.compare_to = getCompareFilter(querySource)?.compare_to
+/** Takes a query and returns an object with "useful" properties that don't contain sensitive data. */
+export function sanitizeQuery(query: Node | null): SanitizedQuery {
+ const payload: SanitizedQuery = {
+ query_kind: query?.kind,
+ query_source_kind: isNodeWithSource(query) ? query.source.kind : undefined,
+ // Whether this insight/query reads from a connector-synced data warehouse source (series-level
+ // detection). Raw SQL/HogQL warehouse usage is flagged from the query response in performQuery.
+ uses_data_warehouse_source: queryUsesDataWarehouse(query),
+ }
- // funnels
- payload.funnel_viz_type = isFunnelsQuery(querySource) ? querySource.funnelsFilter?.funnelVizType : undefined
- payload.funnel_order_type = isFunnelsQuery(querySource) ? querySource.funnelsFilter?.funnelOrderType : undefined
+ const querySource = insightQuerySource(query)
+ if (querySource) {
+ Object.assign(
+ payload,
+ dateRangeAndSamplingProperties(querySource),
+ seriesProperties(querySource),
+ breakdownProperties(querySource),
+ trendsLikeProperties(querySource),
+ funnelProperties(querySource)
+ )
}
return objectClean(payload)
@@ -3409,55 +3492,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
if (!delay) {
await breakpoint(500) // Debounce to avoid noisy events from continuous navigation
}
- const { created_at, is_shared, pinned, creation_mode, id } = dashboard
- const properties: Record<string, any> = {
- created_at,
- is_shared,
- pinned,
- creation_mode,
- viewer_is_creator:
- dashboard.created_by?.uuid && values.user?.uuid
- ? dashboard.created_by?.uuid === values.user?.uuid
- : undefined,
- sample_items_count: 0,
- item_count: dashboard.tiles?.length || 0,
- created_by_system: !dashboard.created_by,
- dashboard_id: id,
- lastRefreshed: lastRefreshed?.toISOString(),
- refreshAge: lastRefreshed ? now().diff(lastRefreshed, 'seconds') : undefined,
- uses_data_warehouse_source: false,
- data_warehouse_tiles_count: 0,
- }
-
- for (const item of dashboard.tiles || []) {
- if (item.insight) {
- const query = isNodeWithSource(item.insight.query) ? item.insight.query.source : item.insight.query
- const key = `${query?.kind || !!item.text ? 'text' : 'empty'}_count`
- if (!properties[key]) {
- properties[key] = 1
- } else {
- properties[key] += 1
- }
- properties.sample_items_count += item.insight.is_sample ? 1 : 0
- if (queryUsesDataWarehouse(item.insight.query)) {
- properties.uses_data_warehouse_source = true
- properties.data_warehouse_tiles_count += 1
- }
- } else if (item.widget) {
- if (!properties['widget_tiles_count']) {
- properties['widget_tiles_count'] = 1
- } else {
- properties['widget_tiles_count'] += 1
- }
- } else {
- if (!properties['text_tiles_count']) {
- properties['text_tiles_count'] = 1
- } else {
- properties['text_tiles_count'] += 1
- }
- }
- }
-
+ const properties = dashboardViewedProperties(dashboard, lastRefreshed, values.user?.uuid)
const eventName = delay ? 'dashboard analyzed' : 'viewed dashboard' // `viewed dashboard` name is kept for backwards compatibility
posthog.capture(eventName, { ...properties, source: 'web' })
},