: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(metrics): capture product intents for alpha (#70183)
Daniel Viscaa01cf429cd40
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 3325451824dc..e57c768f3c45 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -33273,6 +33273,10 @@"logs_set_filters","logs_settings_opened","metrics_docs_viewed",+ "metrics_viewer_query_run",+ "metrics_sql_query_run",+ "metrics_query_saved",+ "metrics_first_ingested","taxonomic filter empty state","create_experiment_from_funnel_button","web_analytics_insight",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 055dff7644a5..460e1c930466 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -8100,6 +8100,10 @@ export enum ProductIntentContext {// MetricsMETRICS_DOCS_VIEWED = 'metrics_docs_viewed',+ METRICS_VIEWER_QUERY_RUN = 'metrics_viewer_query_run',+ METRICS_SQL_QUERY_RUN = 'metrics_sql_query_run',+ METRICS_QUERY_SAVED = 'metrics_query_saved',+ METRICS_FIRST_INGESTED = 'metrics_first_ingested',// Product AnalyticsTAXONOMIC_FILTER_EMPTY_STATE = 'taxonomic filter empty state',diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 19a2354c8347..ee712408dd86 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2789,6 +2789,10 @@ class ProductIntentContext(StrEnum):LOGS_SET_FILTERS = "logs_set_filters"LOGS_SETTINGS_OPENED = "logs_settings_opened"METRICS_DOCS_VIEWED = "metrics_docs_viewed"+ METRICS_VIEWER_QUERY_RUN = "metrics_viewer_query_run"+ METRICS_SQL_QUERY_RUN = "metrics_sql_query_run"+ METRICS_QUERY_SAVED = "metrics_query_saved"+ METRICS_FIRST_INGESTED = "metrics_first_ingested"TAXONOMIC_FILTER_EMPTY_STATE = "taxonomic filter empty state"CREATE_EXPERIMENT_FROM_FUNNEL_BUTTON = "create_experiment_from_funnel_button"WEB_ANALYTICS_INSIGHT = "web_analytics_insight"diff --git a/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.test.ts b/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.test.tsnew file mode 100644index 000000000000..0da9f360fc6c--- /dev/null+++ b/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.test.ts@@ -0,0 +1,52 @@+import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { metricsSqlEditorTrackingLogic } from './metricsSqlEditorTrackingLogic'++jest.mock('posthog-js')++// endpointLogic (pulled in transitively via sqlEditorLogic) uses permanentlyMount() with a+// keyed logic, which crashes in tests without the full React component tree.+jest.mock('lib/utils/kea-logic-builders', () => ({+ ...jest.requireActual('lib/utils/kea-logic-builders'),+ permanentlyMount: () => () => {},+}))++describe('metricsSqlEditorTrackingLogic', () => {+ let logic: ReturnType<typeof metricsSqlEditorTrackingLogic.build>++ // teamLogic is mounted via connect once `logic` mounts, so its actionCreators are available here.+ const sqlRunIntent = (): any =>+ teamLogic.actionCreators.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_SQL_QUERY_RUN,+ })++ beforeEach(() => {+ initKeaTests()+ logic = metricsSqlEditorTrackingLogic({ sqlEditorTabId: 'test-tab' })+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ // The intent feeds the growth team's activation funnel; a renamed or disconnected+ // sqlEditorLogic action would silently stop recording it. The auto-init first run is+ // skipped so it isn't counted as user intent. (Save-as intents aren't covered here:+ // dispatching the real submit actions needs the full data-node logic graph mounted.)+ it('a manual query run records a product intent, the auto-init first run does not', async () => {+ await expectLogic(logic, () => {+ logic.actions.sqlEditorRunQuery()+ }).toNotHaveDispatchedActions([sqlRunIntent()])++ await expectLogic(logic, () => {+ logic.actions.sqlEditorRunQuery()+ }).toDispatchActions([sqlRunIntent()])+ })+})diff --git a/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.ts b/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.tsindex f7d2507a3bb3..8de79514852e 100644--- a/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.ts+++ b/products/metrics/frontend/components/metricsSqlEditorTrackingLogic.ts@@ -4,6 +4,9 @@ import posthog from 'posthog-js'import { SaveAsMenuItem } from 'scenes/data-warehouse/editor/editorSceneLogic'import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'+import { teamLogic } from 'scenes/teamLogic'++import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import type { metricsSqlEditorTrackingLogicType } from './metricsSqlEditorTrackingLogicType'@@ -11,10 +14,6 @@ export interface MetricsSqlEditorTrackingLogicProps {sqlEditorTabId: string}-const captureSaved = (target: SaveAsMenuItem['action']): void => {- posthog.capture('metrics sql query saved', { target })-}-export const metricsSqlEditorTrackingLogic = kea<metricsSqlEditorTrackingLogicType>([path(['products', 'metrics', 'frontend', 'components', 'metricsSqlEditorTrackingLogic']),props({} as MetricsSqlEditorTrackingLogicProps),@@ -28,21 +27,41 @@ export const metricsSqlEditorTrackingLogic = kea<metricsSqlEditorTrackingLogicTy'saveAsInsightSubmit as sqlEditorSaveAsInsightSubmit','saveAsEndpointSubmit as sqlEditorSaveAsEndpointSubmit',],+ teamLogic,+ ['addProductIntent'],],})),- listeners(({ cache }) => ({- sqlEditorRunQuery: () => {- // Skip the auto-init runQuery dispatched by MetricsSqlEditor's first mount.- // Trade-off: on revisit (queryInput already set, no auto-init), the user's first- // manual run is also skipped. Acceptable under-count for an alpha metric.- if (!cache.firstRunSeen) {- cache.firstRunSeen = true- return- }- posthog.capture('metrics sql query run')- },- sqlEditorSaveAsViewSubmit: () => captureSaved('view'),- sqlEditorSaveAsInsightSubmit: () => captureSaved('insight'),- sqlEditorSaveAsEndpointSubmit: () => captureSaved('endpoint'),- })),+ listeners(({ actions, cache }) => {+ // Fires on submit, not on save success: intents measure interest, not achievement+ // (a user who names and submits a save has shown the interest we're after, even if+ // the request then fails), and sqlEditorLogic exposes no per-target success action+ // to gate on. Activation criteria, defined later, count real saved artifacts.+ const trackSaved = (target: SaveAsMenuItem['action']): void => {+ posthog.capture('metrics sql query saved', { target })+ actions.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_QUERY_SAVED,+ metadata: { target },+ })+ }+ return {+ sqlEditorRunQuery: () => {+ // Skip the auto-init runQuery dispatched by MetricsSqlEditor's first mount.+ // Trade-off: on revisit (queryInput already set, no auto-init), the user's first+ // manual run is also skipped. Acceptable under-count for an alpha metric.+ if (!cache.firstRunSeen) {+ cache.firstRunSeen = true+ return+ }+ posthog.capture('metrics sql query run')+ actions.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_SQL_QUERY_RUN,+ })+ },+ sqlEditorSaveAsViewSubmit: () => trackSaved('view'),+ sqlEditorSaveAsInsightSubmit: () => trackSaved('insight'),+ sqlEditorSaveAsEndpointSubmit: () => trackSaved('endpoint'),+ }+ }),])diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.tsindex 8efe44c25262..18da852a3ee9 100644--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts@@ -1,6 +1,9 @@import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'+import { teamLogic } from 'scenes/teamLogic'++import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import {@@ -262,4 +265,31 @@ describe('metricsUsageTrackingLogic', () => {expect(captures(event)).toEqual([[event, expectedProperties]])expect(allCapturedProperties()).not.toContain(SECRET_ATTR_VALUE)})++ // teamLogic is mounted via connect once `logic` mounts, so its actionCreators are available here.+ const viewerQueryIntent = (): any =>+ teamLogic.actionCreators.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_VIEWER_QUERY_RUN,+ })++ // The intent feeds the growth team's activation funnel; losing the dedupe guard would+ // instead spam the product-intent API on every 15s live-refresh poll.+ it('the first real query success records a product intent, once per mount', async () => {+ metricsViewerLogic.actions.setMetricName(SECRET_METRIC)+ await expectLogic(logic, () => {+ metricsViewerLogic.actions.fetchQueryResults({})+ }).toDispatchActions([viewerQueryIntent()])++ // Live refresh re-runs the same query; the intent must not fire again.+ await expectLogic(logic, () => {+ metricsViewerLogic.actions.fetchQueryResults({})+ }).toNotHaveDispatchedActions([viewerQueryIntent()])+ })++ it('the empty-name initial query success records no product intent', async () => {+ await expectLogic(logic, () => {+ metricsViewerLogic.actions.fetchQueryResults({})+ }).toNotHaveDispatchedActions([viewerQueryIntent()])+ })})diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.tsindex 63d12b38d263..63da24733eac 100644--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts@@ -1,7 +1,9 @@import { actions, connect, kea, listeners, path } from 'kea'import posthog from 'posthog-js'-import type { MetricsQuery } from '~/queries/schema/schema-general'+import { teamLogic } from 'scenes/teamLogic'++import { type MetricsQuery, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import type { _MetricEventSampleApi } from 'products/metrics/frontend/generated/api.schemas'@@ -40,6 +42,8 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([],metricsSamplesLogic,['setActiveTab as samplesPanelTabChanged', 'loadSamplesSuccess'],+ teamLogic,+ ['addProductIntent'],],values: [metricsViewerLogic, ['hasMetricName', 'aggregation', 'groupByKeys', 'queryFilters']],})),@@ -48,7 +52,7 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([sampleRowExpanded: (sample: _MetricEventSampleApi) => ({ sample }),tracePivotClicked: (sample: _MetricEventSampleApi) => ({ sample }),}),- listeners(({ values, cache }) => ({+ listeners(({ actions, values, cache }) => ({sceneTabChanged: ({ activeTab }) => {posthog.capture('metrics tab changed', { tab: activeTab })},@@ -116,6 +120,15 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([has_group_by: values.groupByKeys.length > 0,has_filters: values.queryFilters.length > 0,})+ // Once per mount, not per query — live refresh re-runs the query every 15s,+ // and each intent call is an API request (the backend counts repeats itself).+ if (!cache.viewerQueryIntentFired) {+ cache.viewerQueryIntentFired = true+ actions.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_VIEWER_QUERY_RUN,+ })+ }},fetchQueryResultsFailure: ({ error, errorObject }) => {// A superseded/unmounted query aborts — user-initiated, not a failure.diff --git a/products/metrics/frontend/metricsIngestionLogic.test.ts b/products/metrics/frontend/metricsIngestionLogic.test.tsnew file mode 100644index 000000000000..7e49fd8da33e--- /dev/null+++ b/products/metrics/frontend/metricsIngestionLogic.test.ts@@ -0,0 +1,64 @@+import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { metricsHasMetricsRetrieve } from './generated/api'+import { metricsIngestionLogic } from './metricsIngestionLogic'++jest.mock('./generated/api', () => ({+ metricsHasMetricsRetrieve: jest.fn(),+}))++describe('metricsIngestionLogic', () => {+ let logic: ReturnType<typeof metricsIngestionLogic.build>++ // teamLogic is mounted via connect once `logic` mounts, so its actionCreators are available here.+ const firstIngestIntent = (): any =>+ teamLogic.actionCreators.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_FIRST_INGESTED,+ })++ beforeEach(() => {+ localStorage.clear()+ initKeaTests()+ jest.mocked(metricsHasMetricsRetrieve).mockReset()+ })++ afterEach(() => {+ logic?.unmount()+ })++ // Distinguishes a team completing OTel setup mid-session (intent) from a team that simply+ // already had metrics (no intent) — firing on any `true` would mark every long-standing+ // team as newly intending and corrupt the activation funnel.+ it('records a product intent only on an observed no-metrics -> has-metrics transition, once', async () => {+ jest.mocked(metricsHasMetricsRetrieve).mockResolvedValue({ hasMetrics: false } as any)+ logic = metricsIngestionLogic()+ logic.mount()+ await expectLogic(logic)+ .toDispatchActions(['loadTeamHasMetricsSuccess'])+ .toNotHaveDispatchedActions([firstIngestIntent()])++ jest.mocked(metricsHasMetricsRetrieve).mockResolvedValue({ hasMetrics: true } as any)+ await expectLogic(logic, () => {+ logic.actions.loadTeamHasMetrics()+ }).toDispatchActions([firstIngestIntent()])++ await expectLogic(logic, () => {+ logic.actions.loadTeamHasMetrics()+ }).toNotHaveDispatchedActions([firstIngestIntent()])+ })++ it('a team that already has metrics on first check records no intent', async () => {+ jest.mocked(metricsHasMetricsRetrieve).mockResolvedValue({ hasMetrics: true } as any)+ logic = metricsIngestionLogic()+ logic.mount()+ await expectLogic(logic)+ .toDispatchActions(['loadTeamHasMetricsSuccess'])+ .toNotHaveDispatchedActions([firstIngestIntent()])+ })+})diff --git a/products/metrics/frontend/metricsIngestionLogic.tsx b/products/metrics/frontend/metricsIngestionLogic.tsxindex 1ae19691dc34..7160c156a5b0 100644--- a/products/metrics/frontend/metricsIngestionLogic.tsx+++ b/products/metrics/frontend/metricsIngestionLogic.tsx@@ -1,9 +1,11 @@-import { afterMount, connect, kea, path, reducers, selectors } from 'kea'+import { afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { retryWithBackoff } from 'lib/utils/async'import { teamLogic } from 'scenes/teamLogic'+import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { metricsHasMetricsRetrieve } from './generated/api'import type { metricsIngestionLogicType } from './metricsIngestionLogicType'@@ -13,6 +15,7 @@ export const metricsIngestionLogic = kea<metricsIngestionLogicType>([path(['products', 'metrics', 'frontend', 'metricsIngestionLogic']),connect(() => ({values: [teamLogic, ['currentTeamId']],+ actions: [teamLogic, ['addProductIntent']],})),loaders(({ values }) => ({teamHasMetrics: {@@ -45,6 +48,25 @@ export const metricsIngestionLogic = kea<metricsIngestionLogicType>([],}),+ listeners(({ actions, cache }) => ({+ loadTeamHasMetricsSuccess: ({ teamHasMetrics }) => {+ if (!teamHasMetrics) {+ cache.sawNoMetrics = true+ return+ }+ // Only an observed no-metrics -> has-metrics transition is an intent: the user+ // completed external OTel setup during this session. A team whose first check+ // already returns true (or was cached true) just has pre-existing metrics.+ if (cache.sawNoMetrics && !cache.firstIngestIntentFired) {+ cache.firstIngestIntentFired = true+ actions.addProductIntent({+ product_type: ProductKey.METRICS,+ intent_context: ProductIntentContext.METRICS_FIRST_INGESTED,+ })+ }+ },+ })),+selectors({hasMetrics: [(s) => [s.teamHasMetrics, s.cachedTeamHasMetrics],