: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(data-warehouse): track BI editor usage (#78854)
Marius Andra3a59c43d938f
diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorAnalytics.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorAnalytics.tsnew file mode 100644index 000000000000..2649e8a94201--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorAnalytics.ts@@ -0,0 +1,78 @@+import posthog from 'posthog-js'++import { type BIConfig, type BIEditorState, BIEditorView } from './biEditorTypes'++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',+} as const++export type BIEditorSaveType = 'endpoint' | 'insight' | 'metric' | 'view'+export type BIEditorSaveOperation = 'create' | 'update'++function uniqueSorted<T extends string>(values: T[]): T[] {+ return [...new Set(values)].sort()+}++function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown> {+ const fields = [+ ...config.rows,+ ...config.columns,+ ...config.values.map((value) => value.field),+ ...config.filters.map((filter) => filter.field),+ ]+ const customExpressionCount =+ [...config.rows, ...config.columns].filter((field) => !field.name).length ++ config.values.filter((value) => value.aggregation === 'custom').length ++ config.filters.filter((filter) => filter.operator === 'custom').length++ return {+ source_kind: config.source ? (config.source.connectionId ? 'external_connection' : 'project_data') : 'none',+ chart_type: config.chartType,+ row_count: config.rows.length,+ column_count: config.columns.length,+ value_count: config.values.length,+ filter_count: config.filters.length,+ field_types: uniqueSorted(fields.map((field) => field.type)),+ aggregation_types: uniqueSorted(config.values.map((value) => value.aggregation)),+ filter_operator_types: uniqueSorted(config.filters.map((filter) => filter.operator)),+ date_bucket_types: uniqueSorted(+ fields.flatMap((field) => (field.dateBucket === undefined ? [] : [field.dateBucket]))+ ),+ custom_expression_count: customExpressionCount,+ }+}++export function captureBIEditorModeSelected(editorView: BIEditorView, config: BIConfig): void {+ posthog.capture(BI_EDITOR_EVENTS.MODE_SELECTED, {+ mode: editorView,+ ...getBIEditorConfigProperties(config),+ })+}++export function captureBIEditorQueryRun(state: BIEditorState | undefined): void {+ if (state?.editorView !== BIEditorView.BI) {+ return+ }++ posthog.capture(BI_EDITOR_EVENTS.QUERY_RUN, getBIEditorConfigProperties(state.config))+}++export function captureBIEditorQuerySaved(+ state: BIEditorState | undefined,+ saveType: BIEditorSaveType,+ operation: BIEditorSaveOperation,+ addedToDashboard = false+): void {+ if (state?.editorView !== BIEditorView.BI) {+ return+ }++ posthog.capture(BI_EDITOR_EVENTS.QUERY_SAVED, {+ save_type: saveType,+ operation,+ added_to_dashboard: addedToDashboard,+ ...getBIEditorConfigProperties(state.config),+ })+}diff --git a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.tsindex c18a1612e841..b9dcb5d23b6f 100644--- a/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts+++ b/frontend/src/scenes/data-warehouse/editor/bi/biEditorLogic.ts@@ -8,6 +8,7 @@ import { ChartDisplayType } from '~/types'import { sqlEditorLogic } from '../sqlEditorLogic'import type { QueryTab } from '../sqlEditorLogic'+import { captureBIEditorModeSelected } from './biEditorAnalytics'import {BIAggregation,BIConfig,@@ -488,6 +489,7 @@ export const biEditorLogic = kea<biEditorLogicType>([actions.syncUrlWithQuery()},setEditorView: ({ editorView }) => {+ captureBIEditorModeSelected(editorView, values.config)actions.persistState(editorView, values.config)if (editorView === BIEditorView.BI) {actions.syncGeneratedQuery()diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 92f8c742c6d8..2baa0b03e961 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -1,7 +1,9 @@import { router } from 'kea-router'import { expectLogic, partial } from 'kea-test-utils'+import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'import { insightsApi } from 'scenes/insights/utils/api'@@ -26,6 +28,7 @@ import {import { initKeaTests } from '~/test/init'import { ChartDisplayType, InsightShortId, QueryBasedInsightModel } from '~/types'+import { BI_EDITOR_EVENTS } from './bi/biEditorAnalytics'import { biEditorLogic } from './bi/biEditorLogic'import { BIConfig, BIEditorView, BIField } from './bi/biEditorTypes'import { buildSqlNotebook, editorSceneLogic } from './editorSceneLogic'@@ -1506,6 +1509,166 @@ describe('sqlEditorLogic', () => {filters: [{ field: eventField, operator: 'equals', value: 'signup' }],limit: 1000,}+ const configEventProperties = {+ source_kind: 'project_data',+ chart_type: ChartDisplayType.ActionsBar,+ row_count: 1,+ column_count: 0,+ value_count: 0,+ filter_count: 1,+ field_types: ['string'],+ aggregation_types: [],+ filter_operator_types: ['equals'],+ date_bucket_types: [],+ custom_expression_count: 0,+ }++ it('captures BI mode selection and query runs without query contents', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SQL_EDITOR_BI_MODE], {+ [FEATURE_FLAGS.SQL_EDITOR_BI_MODE]: true,+ })+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()++ router.actions.push(urls.sqlEditor(), undefined, {+ q: "SELECT event, count(*) FROM events WHERE event = 'signup' GROUP BY event",+ mode: BIEditorView.BI,+ bi: config,+ })+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])++ ;(posthog.capture as jest.Mock).mockClear()+ biLogic.actions.setEditorView(BIEditorView.SQL)+ expect(posthog.capture).toHaveBeenCalledWith(BI_EDITOR_EVENTS.MODE_SELECTED, {+ mode: BIEditorView.SQL,+ ...configEventProperties,+ })++ ;(posthog.capture as jest.Mock).mockClear()+ biLogic.actions.setEditorView(BIEditorView.BI)+ expect(posthog.capture).toHaveBeenCalledWith(BI_EDITOR_EVENTS.MODE_SELECTED, {+ mode: BIEditorView.BI,+ ...configEventProperties,+ })++ ;(posthog.capture as jest.Mock).mockClear()+ logic.actions.runQuery()+ expect(posthog.capture).toHaveBeenCalledWith(BI_EDITOR_EVENTS.QUERY_RUN, configEventProperties)++ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.SQL_EDITOR_BI_MODE]: false })+ ;(posthog.capture as jest.Mock).mockClear()+ logic.actions.runQuery()+ expect(posthog.capture).not.toHaveBeenCalledWith(BI_EDITOR_EVENTS.QUERY_RUN, expect.anything())++ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SQL_EDITOR_BI_MODE], {+ [FEATURE_FLAGS.SQL_EDITOR_BI_MODE]: true,+ })+ biLogic.actions.setEditorView(BIEditorView.SQL)+ ;(posthog.capture as jest.Mock).mockClear()+ logic.actions.runQuery()+ expect(posthog.capture).not.toHaveBeenCalledWith(BI_EDITOR_EVENTS.QUERY_RUN, expect.anything())++ biLogic.unmount()+ })++ it('captures a successful BI insight save as an activation outcome', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SQL_EDITOR_BI_MODE], {+ [FEATURE_FLAGS.SQL_EDITOR_BI_MODE]: true,+ })+ const createSpy = jest.spyOn(insightsApi, 'create').mockResolvedValue(MOCK_INSIGHT)+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()+ const biLogic = biEditorLogic({ tabId: TAB_ID })+ biLogic.mount()++ router.actions.push(urls.sqlEditor(), undefined, {+ q: "SELECT event, count(*) FROM events WHERE event = 'signup' GROUP BY event",+ mode: BIEditorView.BI,+ bi: config,+ })+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])++ logic.actions.setDashboardId(99)+ ;(posthog.capture as jest.Mock).mockClear()+ logic.actions.saveAsInsightSubmit('BI insight')+ await expectLogic(logic).toFinishAllListeners()++ expect(posthog.capture).toHaveBeenCalledWith(BI_EDITOR_EVENTS.QUERY_SAVED, {+ save_type: 'insight',+ operation: 'create',+ added_to_dashboard: true,+ ...configEventProperties,+ })++ createSpy.mockRestore()+ biLogic.unmount()+ })++ it('attributes a BI view update to its originating tab', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SQL_EDITOR_BI_MODE], {+ [FEATURE_FLAGS.SQL_EDITOR_BI_MODE]: true,+ })+ let resolveFirstViewRequest: () => void = () => {}+ let markFirstViewRequestStarted: () => void = () => {}+ const firstViewRequestStarted = new Promise<void>((resolve) => {+ markFirstViewRequestStarted = resolve+ })+ const firstViewRequestPending = new Promise<void>((resolve) => {+ resolveFirstViewRequest = resolve+ })+ let viewRequestCount = 0+ useMocks({+ get: {+ '/api/environments/:team_id/warehouse_saved_queries/:id/': async () => {+ viewRequestCount += 1+ if (viewRequestCount === 1) {+ markFirstViewRequestStarted()+ await firstViewRequestPending+ }+ return [200, MOCK_VIEW]+ },+ },+ })+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()+ logic.actions.createTab(MOCK_VIEW.query.query, MOCK_VIEW, undefined, undefined, undefined, {+ editorView: BIEditorView.BI,+ config,+ })+ await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])++ ;(posthog.capture as jest.Mock).mockClear()+ logic.actions.updateView({+ id: MOCK_VIEW.id,+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 2' },+ types: [],+ })+ await firstViewRequestStarted+ logic.actions.updateTab({ ...logic.values.activeTab!, biEditorState: undefined })+ resolveFirstViewRequest()+ await expectLogic(logic).toFinishAllListeners()++ expect(posthog.capture).toHaveBeenCalledWith(BI_EDITOR_EVENTS.QUERY_SAVED, {+ save_type: 'view',+ operation: 'update',+ added_to_dashboard: false,+ ...configEventProperties,+ })+ })it('offers every sidebar table while excluding hidden PostHog tables', () => {const biLogic = biEditorLogic({ tabId: TAB_ID })diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 2ee6a6ca7fdc..079c82435f34 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -101,6 +101,7 @@ import type { DataModelingDAG, DataWarehouseSavedQueryFolder, UserType } from '.import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'import { validateSavedQueryName } from '../saved_queries/savedQueryNameValidation'import { dataModelingLogic } from '../scene/dataModelingLogic'+import { captureBIEditorQueryRun, captureBIEditorQuerySaved } from './bi/biEditorAnalytics'import { BIEditorState, parseBIEditorState } from './bi/biEditorTypes'import { connectionSelectorLogic } from './connectionSelectorLogic'import { draftsLogic } from './draftsLogic'@@ -1069,8 +1070,10 @@ export interface sqlEditorLogicActions {}updateViewSuccess: (view: UpdateViewPayload,- draftId?: string+ draftId?: string,+ biEditorState?: BIEditorState) => {+ biEditorState: BIEditorState | undefineddraftId: string | undefinedview: UpdateViewPayload}@@ -1348,9 +1351,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([view,draftId,}),- updateViewSuccess: (view: UpdateViewPayload, draftId?: string) => ({+ updateViewSuccess: (view: UpdateViewPayload, draftId?: string, biEditorState?: BIEditorState) => ({view,draftId,+ biEditorState,}),setUpstreamViewMode: (mode: 'graph' | 'table') => ({ mode }),setHoveredNode: (nodeId: string | null) => ({ nodeId }),@@ -1677,6 +1681,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([return resolveSaveCandidatesPure(fullText, cursorOffset, selectionText)}+ const getActiveBIEditorState = (): BIEditorState | undefined =>+ values.featureFlags[FEATURE_FLAGS.SQL_EDITOR_BI_MODE] ? values.activeTab?.biEditorState : undefinedreturn {fixErrorsSuccess: ({ response }) => {@@ -1999,6 +2005,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})},runQuery: ({ queryOverride, switchTab }) => {+ captureBIEditorQueryRun(getActiveBIEditorState())+let query: stringif (queryOverride) {// Explicit override (e.g. user selected text and pressed Cmd+Enter)@@ -2275,6 +2283,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([isTest = false,queryOverride,}) => {+ const biEditorState = getActiveBIEditorState()const query: HogQLQuery = values.sourceQuery.sourceconst queryToSave = normalizeRawQuerySource({@@ -2310,6 +2319,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([...(dagId ? { dag_id: dagId } : {}),...(isTest ? { is_test: true } : {}),})+ captureBIEditorQuerySaved(biEditorState, 'view', 'create')// Saved queries are unique by team,nameconst savedQuery = dataWarehouseViewsLogic.values.dataWarehouseSavedQueries.find(@@ -2434,6 +2444,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})},saveAsInsightSubmit: async ({ name, queryOverride }) => {+ const biEditorState = getActiveBIEditorState()const currentVisualizationQuery = getCurrentVisualizationQuery(values.dataLogicKey, values.sourceQuery)const effectiveVisualizationType = dataVisualizationLogic.findMounted({key: values.dataLogicKey,@@ -2464,6 +2475,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([saved: true,...(dashboardId ? { dashboards: [dashboardId] } : {}),})+ captureBIEditorQuerySaved(biEditorState, 'insight', 'create', dashboardId !== null)const logic = insightLogic({dashboardItemId: insight.short_id,doNotLoad: true,@@ -2537,6 +2549,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})},saveAsEndpointSubmit: async ({ name, description, queryOverride }) => {+ const biEditorState = getActiveBIEditorState()try {const endpoint = await api.endpoint.create({name: slugify(name),@@ -2546,6 +2559,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([query: queryOverride ?? values.queryInput ?? '',}),})+ captureBIEditorQuerySaved(biEditorState, 'endpoint', 'create')lemonToast.success('Endpoint created')globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.CreateFirstEndpoint)router.actions.push(urls.endpoint(endpoint.name))@@ -2584,6 +2598,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})},saveAsMetricSubmit: async ({ name, description, queryOverride }) => {+ const biEditorState = getActiveBIEditorState()try {const metric = await dataCatalogMetricsCreate(String(ApiConfig.getCurrentTeamId()), {name,@@ -2593,6 +2608,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([query: queryOverride ?? values.queryInput ?? '',}) as unknown as Record<string, unknown>,})+ captureBIEditorQuerySaved(biEditorState, 'metric', 'create')lemonToast.success('Metric created')router.actions.push(urls.dataCatalogMetric(metric.name))} catch (error: any) {@@ -2604,6 +2620,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([return}actions.setMetricUpdating(true)+ const biEditorState = getActiveBIEditorState()try {await dataCatalogMetricsPartialUpdate(String(ApiConfig.getCurrentTeamId()),@@ -2615,6 +2632,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([}) as unknown as Record<string, unknown>,})+ captureBIEditorQuerySaved(biEditorState, 'metric', 'update')lemonToast.success('Metric updated')router.actions.push(urls.dataCatalogMetric(values.editingMetricName))} catch (error: any) {@@ -2644,6 +2662,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([}actions.setInsightLoading(true)+ const biEditorState = getActiveBIEditorState()const insightName = values.activeTab?.nameconst insightDescription = values.activeTab?.description@@ -2679,6 +2698,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([throw e}actions.setInsightLoading(false)+ captureBIEditorQuerySaved(biEditorState, 'insight', 'update', dashboardId !== null)if (values.activeTab) {actions.updateTab({@@ -2830,6 +2850,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})},updateView: async ({ view, draftId }) => {+ const biEditorState = getActiveBIEditorState()const latestView = await api.dataWarehouseSavedQueries.get(view.id)// A real conflict means someone else changed the query text since this edit began.// Detect it by comparing the server's current query against the baseline this edit@@ -2856,7 +2877,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([...view,edited_history_id: latestView?.latest_history_id,})- actions.updateViewSuccess(view, draftId)+ actions.updateViewSuccess(view, draftId, biEditorState)},onReject: () => {},})@@ -2868,10 +2889,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([...view,edited_history_id: latestView?.latest_history_id ?? view.edited_history_id,})- actions.updateViewSuccess(view, draftId)+ actions.updateViewSuccess(view, draftId, biEditorState)}},- updateViewSuccess: async ({ view, draftId }) => {+ updateViewSuccess: async ({ view, draftId, biEditorState }) => {+ captureBIEditorQuerySaved(biEditorState, 'view', 'update')if (draftId) {actions.deleteDraft(draftId, view?.name)}