: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
feat(bi): track worksheet funnel and feature usage (#113183)
Marius Andra2b9ef2dbc197
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.mdindex 997010cb781e..61a4d858b1b3 100644--- a/docs/published/handbook/engineering/data-warehouse.md+++ b/docs/published/handbook/engineering/data-warehouse.md@@ -30,6 +30,8 @@ Choose a connection in the **Data** panel, then select a table below it. **Run****Auto update** is off by default and remembers your choice. Selecting a table alone can run a count when you click **Run**. In wide worksheets, drag the divider between the data and analysis panels to resize the data panel, or drag the analysis panel's right edge to resize that panel independently.+BI usage keeps the existing `sql-editor-bi-mode-selected`, `sql-editor-bi-query-run`, and `sql-editor-bi-query-saved` events. Their properties describe table calculations, Top N, comparisons, formatting, axes, totals, and related/property field counts. The `bi-worksheet-action` event's `action` property defines the funnel: `opened`, `source_selected`, `first_chart`, `saved`, `added_to_dashboard`. The first chart is the first nonempty successful result per editor visit; reruns and failures do not count again. Saved and dashboard steps include `insight_id`. Additional actions record drill-down choices, related-table expansion, and property browsing/search. These events exclude SQL, source names, field names, formulas, search text, filter values, and result contents.+For older saves without worksheet configuration, discarding query edits preserves the current source and shelves.SQL query-scan advisories are hidden in Business intelligence. Query errors and warnings about stale sources or restricted data remain visible.diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 1adc594f42d4..267c92388e1a 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -32,6 +32,7 @@ import {Node,NodeKind,} from '~/queries/schema/schema-general'+import { isBIVisualizationNode } from '~/queries/utils'import {getBreakdown,getCompareFilter,@@ -73,6 +74,7 @@ import {SurveyQuestionType,} from '~/types'+import { captureBIWorksheetAction } from 'products/business_intelligence/frontend/biEditorAnalytics'import { getExperimentStatus } from 'products/experiments/frontend/experimentStatus'import type { ExperimentMetricUnion } from '../../queries/schema/schema-general'@@ -2542,6 +2544,9 @@ export const eventUsageLogic = kea<eventUsageLogicType>([posthog.capture('dashboard add menu opened', { source, dashboard_id: dashboardId })},reportSavedInsightToDashboard: async ({ insight, dashboardId }) => {+ if (isBIVisualizationNode(insight?.query)) {+ captureBIWorksheetAction('added_to_dashboard', insight.query.config, { insight_id: insight.id })+ }posthog.capture('saved insight to dashboard', {insight: sanitizeInsight(insight),dashboard_id: dashboardId,diff --git a/products/business_intelligence/frontend/BIDrilldownModal.tsx b/products/business_intelligence/frontend/BIDrilldownModal.tsxindex 6de007ea350b..853c68cc72cc 100644--- a/products/business_intelligence/frontend/BIDrilldownModal.tsx+++ b/products/business_intelligence/frontend/BIDrilldownModal.tsx@@ -5,8 +5,10 @@ import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'import { urls } from 'scenes/urls'import { Query } from '~/queries/Query/Query'+import { NodeKind } from '~/queries/schema/schema-general'import { BIDrilldownProps, biDrilldownLogic } from './biDrilldownLogic'+import { captureBIWorksheetAction } from './biEditorAnalytics'export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldownProps }): JSX.Element {const { selection, queries, showRows } = useValues(biDrilldownLogic(props))@@ -31,7 +33,12 @@ export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldow<div className="flex flex-wrap gap-2"><LemonButtontype="primary"- onClick={close}+ onClick={() => {+ if (props.query.kind === NodeKind.BIVisualizationNode) {+ captureBIWorksheetAction('drilldown_worksheet_opened', props.query.config)+ }+ close()+ }}to={queries.worksheet? `${urls.businessIntelligence()}#q=${encodeURIComponent(JSON.stringify(queries.worksheet))}`@@ -52,7 +59,16 @@ export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldow>View underlying rows</LemonButton>- <LemonButton type="secondary" to={urls.sqlEditor({ query: queries.rows })} onClick={close}>+ <LemonButton+ type="secondary"+ to={urls.sqlEditor({ query: queries.rows })}+ onClick={() => {+ if (props.query.kind === NodeKind.BIVisualizationNode) {+ captureBIWorksheetAction('drilldown_sql_opened', props.query.config)+ }+ close()+ }}+ >Open in SQL editor</LemonButton></div>diff --git a/products/business_intelligence/frontend/biConnectionsLogic.ts b/products/business_intelligence/frontend/biConnectionsLogic.tsindex cc5635d2eb50..b1f01ac05a01 100644--- a/products/business_intelligence/frontend/biConnectionsLogic.ts+++ b/products/business_intelligence/frontend/biConnectionsLogic.ts@@ -26,6 +26,8 @@ import {import type { BIConnection } from 'products/business_intelligence/frontend/biConnectionTree'import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'+import { captureBIWorksheetAction } from './biEditorAnalytics'+export interface BIConnectionsLogicProps {tabId: string}@@ -158,6 +160,9 @@ export const biConnectionsLogic: LogicWrapper<biConnectionsLogicType> = kea<biCo}},toggleConnection: ({ id, tableName }) => {+ if (values.expandedIds.includes(id)) {+ captureBIWorksheetAction('related_table_expanded', values.config)+ }if (tableName && values.expandedIds.includes(id)) {actions.hydrateTableFields([tableName])}diff --git a/products/business_intelligence/frontend/biDrilldownLogic.ts b/products/business_intelligence/frontend/biDrilldownLogic.tsindex 353136cae095..926343eed24b 100644--- a/products/business_intelligence/frontend/biDrilldownLogic.ts+++ b/products/business_intelligence/frontend/biDrilldownLogic.ts@@ -1,8 +1,9 @@-import { MakeLogicType, actions, kea, key, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, kea, key, path, props, reducers, selectors, listeners } from 'kea'import { VisualizationNode, NodeKind, DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'import { BIDrillSelection, getBIDrillQueries, getBIDrillSelection, getBIEffectiveQuery } from './biDrilldown'+import { captureBIWorksheetAction } from './biEditorAnalytics'export interface BIDrilldownProps {key: string@@ -87,4 +88,20 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([selection ? getBIDrillQueries(query, selection) : null,],}),+ listeners(({ values }) => ({+ inspect: () => {+ if (values.query.kind === NodeKind.BIVisualizationNode && values.selection) {+ captureBIWorksheetAction('drilldown_opened', values.query.config, {+ previous_period: values.selection.previous,+ })+ }+ },+ viewRows: () => {+ if (values.query.kind === NodeKind.BIVisualizationNode) {+ captureBIWorksheetAction('underlying_rows_viewed', values.query.config, {+ previous_period: values.selection?.previous,+ })+ }+ },+ })),])diff --git a/products/business_intelligence/frontend/biEditorAnalytics.test.ts b/products/business_intelligence/frontend/biEditorAnalytics.test.tsnew file mode 100644index 000000000000..0f30fb989749--- /dev/null+++ b/products/business_intelligence/frontend/biEditorAnalytics.test.ts@@ -0,0 +1,63 @@+import posthog from 'posthog-js'++import {+ BI_EDITOR_EVENTS,+ captureBIEditorQueryRun,+ captureBIEditorQuerySaved,+ captureBIWorksheetAction,+} from './biEditorAnalytics'+import { BIEditorView, DEFAULT_BI_CONFIG } from './biEditorTypes'++describe('BI usage tracking', () => {+ it('records capabilities while excluding worksheet contents from every event', () => {+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()+ const field = {+ id: 'private-field',+ name: 'properties.private-field',+ expression: 'properties.private-field',+ type: 'float' as const,+ source: { table: 'private-source' },+ }+ const config = {+ ...DEFAULT_BI_CONFIG,+ source: field.source,+ rows: [field],+ values: [+ {+ field,+ aggregation: 'custom' as const,+ customExpression: 'sum(private-formula)',+ label: 'private-label',+ tableCalculation: { type: 'running_total' as const },+ formatting: { prefix: 'private-prefix' },+ },+ ],+ filters: [{ field, operator: 'equals' as const, value: 'private-value' }],+ topN: { fieldId: field.id, count: 5, measureIndex: 0, includeOther: true },+ compareFilter: { compare: true },+ }+ try {+ const state = { editorView: BIEditorView.BI, config }+ captureBIEditorQueryRun(state)+ captureBIEditorQuerySaved(state, 'insight', 'create')+ captureBIWorksheetAction('drilldown_opened', config)+ expect(capture.mock.calls.map(([event]) => event)).toEqual([+ BI_EDITOR_EVENTS.QUERY_RUN,+ BI_EDITOR_EVENTS.QUERY_SAVED,+ BI_EDITOR_EVENTS.WORKSHEET_ACTION,+ ])+ for (const [, properties] of capture.mock.calls) {+ expect(properties).toMatchObject({+ table_calculation_types: ['running_total'],+ top_n_enabled: true,+ comparison_enabled: true,+ formatted_measure_count: 1,+ property_field_count: 3,+ })+ expect(JSON.stringify(properties)).not.toContain('private-')+ }+ } finally {+ capture.mockRestore()+ }+ })+})diff --git a/products/business_intelligence/frontend/biEditorAnalytics.ts b/products/business_intelligence/frontend/biEditorAnalytics.tsindex e6c540d443d0..2910861e78b8 100644--- a/products/business_intelligence/frontend/biEditorAnalytics.ts+++ b/products/business_intelligence/frontend/biEditorAnalytics.ts@@ -8,6 +8,7 @@ export const BI_EDITOR_EVENTS = {MODE_SELECTED: 'sql-editor-bi-mode-selected',QUERY_RUN: 'sql-editor-bi-query-run',QUERY_SAVED: 'sql-editor-bi-query-saved',+ WORKSHEET_ACTION: 'bi-worksheet-action',} as constexport type BIEditorSaveType = 'endpoint' | 'insight' | 'metric' | 'view'@@ -43,11 +44,60 @@ function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown>fields.flatMap((field) => (field.dateBucket === undefined ? [] : [field.dateBucket]))),custom_expression_count: customExpressionCount,+ table_calculation_types: uniqueSorted(+ config.values.flatMap((value) => (value.tableCalculation ? [value.tableCalculation.type] : []))+ ),+ top_n_enabled: !!config.topN,+ top_n_count: config.topN?.count ?? null,+ top_n_include_other: config.topN?.includeOther ?? false,+ comparison_enabled: !!config.compareFilter?.compare,+ comparison_period: config.compareFilter?.compare+ ? config.compareFilter.compare_to+ ? 'custom_offset'+ : 'previous_period'+ : null,+ formatted_measure_count: config.values.filter((value) => value.formatting).length,+ measure_display_types: uniqueSorted(+ config.values.flatMap((value) => (value.display?.displayType ? [value.display.displayType] : []))+ ),+ secondary_axis_count: config.values.filter((value) => value.display?.yAxisPosition === 'right').length,+ totals_enabled: !!(config.totals?.rows || config.totals?.columns || config.totals?.subtotals),+ related_field_count: fields.filter((field) => field.name.includes('.') && !field.name.startsWith('properties.'))+ .length,+ property_field_count: fields.filter(+ (field) => field.name.startsWith('properties.') || field.name.includes('.properties.')+ ).length,sort_kind: config.sort ? 'manual' : 'auto',sort_direction: config.sort?.direction ?? null,}}+export type BIWorksheetAction =+ | 'opened'+ | 'source_selected'+ | 'first_chart'+ | 'saved'+ | 'added_to_dashboard'+ | 'drilldown_opened'+ | 'underlying_rows_viewed'+ | 'drilldown_worksheet_opened'+ | 'drilldown_sql_opened'+ | 'related_table_expanded'+ | 'properties_browsed'+ | 'properties_searched'++export function captureBIWorksheetAction(+ action: BIWorksheetAction,+ config: BIConfig,+ context: { insight_id?: number; previous_period?: boolean; result_count?: number } = {}+): void {+ posthog.capture(BI_EDITOR_EVENTS.WORKSHEET_ACTION, {+ action,+ ...getBIEditorConfigProperties(config),+ ...context,+ })+}+export function captureBIEditorModeSelected(editorView: BIEditorView, config: BIConfig): void {posthog.capture(BI_EDITOR_EVENTS.MODE_SELECTED, {mode: editorView,diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.tsindex dba5e41c8a13..4d86ad427f02 100644--- a/products/business_intelligence/frontend/biEditorLogic.ts+++ b/products/business_intelligence/frontend/biEditorLogic.ts@@ -22,7 +22,10 @@ import {import { CompareFilter, DatabaseSchemaTable, DateRange } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'-import { captureBIEditorModeSelected } from 'products/business_intelligence/frontend/biEditorAnalytics'+import {+ captureBIEditorModeSelected,+ captureBIWorksheetAction,+} from 'products/business_intelligence/frontend/biEditorAnalytics'import {BIChartFit,BIDataPaneFields,@@ -943,7 +946,10 @@ export const biEditorLogic = kea<biEditorLogicType>([setDateRange: () => actions.runAfterChange(),setCompareFilter: () => actions.runAfterChange(),setDateField: () => actions.runAfterChange(),- setDataSource: () => actions.runAfterChange(),+ setDataSource: () => {+ captureBIWorksheetAction('source_selected', values.config)+ actions.runAfterChange()+ },setValueAggregation: () => actions.runAfterChange(),setTableCalculation: () => actions.runAfterChange(),setTopN: () => actions.runAfterChange(),diff --git a/products/business_intelligence/frontend/biPropertyFieldsLogic.ts b/products/business_intelligence/frontend/biPropertyFieldsLogic.tsindex e0f3c1b4eb1a..1b0f50b37f03 100644--- a/products/business_intelligence/frontend/biPropertyFieldsLogic.ts+++ b/products/business_intelligence/frontend/biPropertyFieldsLogic.ts@@ -21,6 +21,8 @@ import * as api from '~/generated/core/api'import { PaginatedEnterprisePropertyDefinitionListApi } from '~/generated/core/api.schemas'import { BIField } from '~/queries/schema/schema-business-intelligence'+import { captureBIWorksheetAction } from './biEditorAnalytics'+import { biEditorLogic } from './biEditorLogic'import { buildBIPropertyFields, getBIPropertyTarget } from './biPropertyFields'export interface BIPropertyFieldsLogicProps {@@ -136,6 +138,13 @@ export const biPropertyFieldsLogic: LogicWrapper<biPropertyFieldsLogicType> = keif (searchVersion !== cache.searchVersion) {return values.page}+ const editor = biEditorLogic.findMounted({ tabId: props.tabId })+ if (offset === 0 && editor) {+ captureBIWorksheetAction(+ values.search.trim() ? 'properties_searched' : 'properties_browsed',+ editor.values.config+ )+ }return {...response,results: [...(offset ? (values.page?.results ?? []) : []), ...response.results],diff --git a/products/business_intelligence/frontend/biSceneLogic.test.ts b/products/business_intelligence/frontend/biSceneLogic.test.tsindex b323292d94fa..d9017683cd82 100644--- a/products/business_intelligence/frontend/biSceneLogic.test.ts+++ b/products/business_intelligence/frontend/biSceneLogic.test.ts@@ -1,5 +1,6 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { urls } from 'scenes/urls'@@ -13,6 +14,7 @@ import { ChartDisplayType, PropertyFilterType, PropertyOperator } from '~/types'import { claimConnectionScope, releaseConnectionScope } from 'products/data_warehouse/frontend/shared/connectionScope'+import { BI_EDITOR_EVENTS } from './biEditorAnalytics'import { biEditorLogic } from './biEditorLogic'import { BIEditorView, buildBIQuery } from './biEditorTypes'import { biSceneLogic } from './biSceneLogic'@@ -127,6 +129,35 @@ describe('biSceneLogic', () => {expect(logic.values.lastRunQuery?.source.query).toContain('count(*) AS count')})+ it('tracks the first successful chart once, without counting empty results or reruns', async () => {+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()+ logic.actions.restoreWorksheet(worksheet())+ const data = dataNodeLogic({+ key: logic.values.dataNodeKey,+ query: logic.values.worksheet.source,+ autoLoad: false,+ })+ data.mount()+ try {+ data.actions.loadDataSuccess({ results: [], columns: ['count'], types: ['Int64'] })+ expect(capture).not.toHaveBeenCalledWith(+ BI_EDITOR_EVENTS.WORKSHEET_ACTION,+ expect.objectContaining({ action: 'first_chart' })+ )+ data.actions.loadDataSuccess({ results: [[3]], columns: ['count'], types: ['Int64'] })+ data.actions.loadDataSuccess({ results: [[4]], columns: ['count'], types: ['Int64'] })+ expect(+ capture.mock.calls.filter(+ ([event, properties]) =>+ event === BI_EDITOR_EVENTS.WORKSHEET_ACTION && properties?.action === 'first_chart'+ )+ ).toHaveLength(1)+ } finally {+ capture.mockRestore()+ data.unmount()+ }+ })+it.each([false, true])('releases its connection scope without disrupting another owner: %s', async (shared) => {const database = databaseTableListLogic()database.mount()diff --git a/products/business_intelligence/frontend/biSceneLogic.ts b/products/business_intelligence/frontend/biSceneLogic.tsindex 519b380e3437..b9a30d23fc68 100644--- a/products/business_intelligence/frontend/biSceneLogic.ts+++ b/products/business_intelligence/frontend/biSceneLogic.ts@@ -40,7 +40,7 @@ import { BIVisualizationNodeApi, InsightApi } from 'products/product_analytics/fimport type { BIConfig } from '../../../frontend/src/queries/schema/schema-business-intelligence'import type { DataWarehouseSavedQueryApi } from '../../data_warehouse/frontend/generated/api.schemas'import type { ExternalDataSourceConnectionOptionApi } from '../../warehouse_sources/frontend/generated/api.schemas'-import { captureBIEditorQueryRun, captureBIEditorQuerySaved } from './biEditorAnalytics'+import { captureBIEditorQueryRun, captureBIEditorQuerySaved, captureBIWorksheetAction } from './biEditorAnalytics'import { biEditorLogic } from './biEditorLogic'import {BIEditorView,@@ -288,6 +288,10 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType? await insightsPartialUpdate(String(values.currentTeamId), values.insight.id, payload): await insightsCreate(String(values.currentTeamId), payload)captureBIEditorQuerySaved(state, 'insight', operation, !!payload.dashboards?.length)+ captureBIWorksheetAction('saved', state.config, { insight_id: insight.id })+ if (payload.dashboards?.length) {+ captureBIWorksheetAction('added_to_dashboard', state.config, { insight_id: insight.id })+ }return insight},},@@ -386,6 +390,23 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType],}),listeners(({ actions, values, props, cache }) => ({+ [dataNodeLogic({ key: `InsightViz.new-bi-${props.tabId}`, query: emptyWorksheet().source }).actionTypes+ .loadDataSuccess]: ({ response }) => {+ if (+ !cache.firstChartCaptured &&+ values.lastRunQuery &&+ response &&+ 'results' in response &&+ Array.isArray(response.results) &&+ response.results.length+ ) {+ cache.firstChartCaptured = true+ captureBIWorksheetAction('first_chart', values.lastRunQuery.config, {+ insight_id: values.insight?.id,+ result_count: response.results.length,+ })+ }+ },resetConfig: () => {actions.restoreWorksheet({...emptyWorksheet(),@@ -577,7 +598,8 @@ export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicTypedatabaseTableListLogic.actions.resetConnectionScope()}}),- afterMount(({ actions }) => {+ afterMount(({ actions, values }) => {+ captureBIWorksheetAction('opened', values.config)connectionSelectorLogic.actions.maybeLoadConnectionOptions()actions.openWorksheet()}),