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(experiments): track health findings and every launch path (#110279)

Marcel Poelkerad57586a18f9
diff --git a/frontend/src/lib/utils/eventUsageLogic.test.ts b/frontend/src/lib/utils/eventUsageLogic.test.ts
index 60c9bdb07047..0d11c3fd8181 100644
--- a/frontend/src/lib/utils/eventUsageLogic.test.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.test.ts
@@ -68,6 +68,30 @@ describe('eventUsageLogic', () => {
})
})
+ describe('experiments list viewed', () => {
+ it('sends the state of the list under its pinned property names', () => {
+ initKeaTests()
+ eventUsageLogic.mount()
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+
+ eventUsageLogic.actions.reportExperimentsListViewed({
+ experimentsShown: 2,
+ statusFilter: 'running',
+ page: 2,
+ hasSearch: true,
+ archived: true,
+ })
+
+ expect(capture.mock.calls.map(([event, properties]) => [event, properties])).toEqual([
+ [
+ 'experiments list viewed',
+ { experiments_shown: 2, status_filter: 'running', page: 2, has_search: true, archived: true },
+ ],
+ ])
+ capture.mockRestore()
+ })
+ })
+
describe('ExperimentMetric (new format)', () => {
it('extracts funnel metric properties', () => {
const metric: ExperimentFunnelMetric = {
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index bd6de85acae2..edca88c4ab32 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -72,6 +72,8 @@ import {
SurveyQuestionType,
} from '~/types'
+import { getExperimentStatus } from 'products/experiments/frontend/experimentStatus'
+
import type { ExperimentMetricUnion } from '../../queries/schema/schema-general'
import type { FunnelCorrelationResultsType, Realm, UserType } from '../../types'
@@ -1264,6 +1266,19 @@ export interface eventUsageLogicActions {
reportExperimentsListAiBadgeClicked: () => {
value: true
}
+ reportExperimentsListViewed: (listView: {
+ archived: boolean
+ experimentsShown: number
+ hasSearch: boolean
+ page: number
+ statusFilter: string
+ }) => {
+ archived: boolean
+ experimentsShown: number
+ hasSearch: boolean
+ page: number
+ statusFilter: string
+ }
reportFeatureFlagBulkCopy: (
flagCount: number,
projectCount: number,
@@ -1917,6 +1932,13 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
reportExperimentWizardStarted: true,
reportExperimentWizardAskAiClicked: (currentStep: string) => ({ currentStep }),
reportExperimentsListAiBadgeClicked: true,
+ reportExperimentsListViewed: (listView: {
+ experimentsShown: number
+ statusFilter: string
+ page: number
+ hasSearch: boolean
+ archived: boolean
+ }) => listView,
reportExperimentViewed: (experiment: Experiment, duration: number | null) => ({ experiment, duration }),
reportExperimentMetricBreakdownAdded: (
experiment: Experiment,
@@ -2558,9 +2580,20 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
reportExperimentsListAiBadgeClicked: () => {
posthog.capture('experiments list ai badge clicked')
},
+ reportExperimentsListViewed: ({ experimentsShown, statusFilter, page, hasSearch, archived }) => {
+ posthog.capture('experiments list viewed', {
+ experiments_shown: experimentsShown,
+ status_filter: statusFilter,
+ page,
+ has_search: hasSearch,
+ archived,
+ })
+ },
reportExperimentViewed: ({ experiment, duration }) => {
posthog.capture('experiment viewed', {
...getEventPropertiesForExperiment(experiment),
+ experiment_id: experiment.id,
+ experiment_status: getExperimentStatus(experiment),
duration,
})
},
diff --git a/frontend/src/scenes/experiments/Experiment.test.tsx b/frontend/src/scenes/experiments/Experiment.test.tsx
index f36fa2f363b3..4e769d104890 100644
--- a/frontend/src/scenes/experiments/Experiment.test.tsx
+++ b/frontend/src/scenes/experiments/Experiment.test.tsx
@@ -1,7 +1,9 @@
import '@testing-library/jest-dom'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { router } from 'kea-router'
+import posthog from 'posthog-js'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
@@ -150,6 +152,7 @@ describe('Experiment component', () => {
sessionStorage.clear()
useMocks(mockApiForExperiment(experimentData))
mountKeaLogics()
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
const { sceneLogic } = renderExperimentViewPage(experimentData)
@@ -170,10 +173,28 @@ describe('Experiment component', () => {
expect(document.querySelector('[data-attr="launch-experiment"]')).not.toBeInTheDocument()
}
+ const shownFindingCodes = captureSpy.mock.calls
+ .filter(([event]) => event === 'experiment health finding shown')
+ .map(([, properties]) => properties?.finding_code)
+
+ await userEvent.click(screen.getAllByText('Add secondary metric')[0])
+ await userEvent.click(screen.getAllByText('Add primary metric')[0])
+ const actedOn = captureSpy.mock.calls
+ .filter(([event]) => event === 'experiment health finding acted on')
+ .map(([, properties]) => [properties?.finding_code, properties?.action_kind])
+
if (expectWarningBanner) {
expect(screen.getByText('No metrics defined')).toBeInTheDocument()
+ // The fixture has no feature flag, so the flag-state banner renders too.
+ expect(shownFindingCodes).toEqual(expect.arrayContaining(['no_metric', 'flag_off_while_running']))
+ expect(actedOn).toEqual([
+ ['no_metric', 'add_secondary_metric'],
+ ['no_metric', 'add_primary_metric'],
+ ])
} else {
expect(screen.queryByText('No metrics defined')).not.toBeInTheDocument()
+ expect(shownFindingCodes).toEqual([])
+ expect(actedOn).toEqual([])
}
cleanupKea(sceneLogic)
diff --git a/frontend/src/scenes/experiments/ExperimentForm/MetricsPanel/EmptyMetricsPanel.tsx b/frontend/src/scenes/experiments/ExperimentForm/MetricsPanel/EmptyMetricsPanel.tsx
index 0bc614cad502..21df5cbea5c8 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/MetricsPanel/EmptyMetricsPanel.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/MetricsPanel/EmptyMetricsPanel.tsx
@@ -5,20 +5,30 @@ import { LemonBanner } from '@posthog/lemon-ui'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { METRIC_CONTEXTS } from 'products/experiments/frontend/modals/ExperimentMetricModal/experimentMetricModalLogic'
+import {
+ METRIC_CONTEXTS,
+ type MetricContext,
+} from 'products/experiments/frontend/modals/ExperimentMetricModal/experimentMetricModalLogic'
import { metricSourceModalLogic } from 'products/experiments/frontend/modals/MetricSourceModal/metricSourceModalLogic'
export const EmptyMetricsPanel = ({
helpText,
isLaunched,
showHelpText = true,
+ onAddMetric,
}: {
helpText?: string
isLaunched?: boolean
showHelpText?: boolean
+ onAddMetric?: (metricType: MetricContext['type']) => void
} = {}): JSX.Element => {
const { openMetricSourceModal } = useActions(metricSourceModalLogic)
+ const addMetric = (context: MetricContext): void => {
+ onAddMetric?.(context.type)
+ openMetricSourceModal(context)
+ }
+
return (
<div className="flex flex-col gap-4">
{isLaunched && (
@@ -38,7 +48,7 @@ export const EmptyMetricsPanel = ({
<LemonButton
type="secondary"
icon={<IconPlus />}
- onClick={() => openMetricSourceModal(METRIC_CONTEXTS.primary)}
+ onClick={() => addMetric(METRIC_CONTEXTS.primary)}
className="!h-[80px] flex-1 @xl:w-[280px] @xl:flex-none"
>
<div className="flex flex-col gap-0.5 text-left">
@@ -49,7 +59,7 @@ export const EmptyMetricsPanel = ({
<LemonButton
type="secondary"
icon={<IconPlus />}
- onClick={() => openMetricSourceModal(METRIC_CONTEXTS.secondary)}
+ onClick={() => addMetric(METRIC_CONTEXTS.secondary)}
className="!h-[80px] flex-1 @xl:w-[280px] @xl:flex-none"
>
<div className="flex flex-col gap-0.5 text-left">
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx
index 8169d0ba7d19..bd891195513f 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx
@@ -12,6 +12,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { ActivityScope } from '~/types'
import { ExperimentMetaBar } from 'products/experiments/frontend/components/ExperimentMetaBar'
+import { useHealthFindingReporting } from 'products/experiments/frontend/health/useHealthFindingReporting'
import { LegacyExperimentView } from 'products/experiments/frontend/legacy'
import { ExperimentMetricModal } from 'products/experiments/frontend/modals/ExperimentMetricModal/ExperimentMetricModal'
import { experimentMetricModalLogic } from 'products/experiments/frontend/modals/ExperimentMetricModal/experimentMetricModalLogic'
@@ -52,6 +53,11 @@ const MetricsTab = (): JSX.Element => {
const hasMetrics = orderedPrimaryMetricsWithResults.length > 0 || orderedSecondaryMetricsWithResults.length > 0
const showRecalculationStatus = !!featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION] && hasMetrics
+ // The condition under which EmptyMetricsPanel renders its "No metrics defined" warning below.
+ const { reportActedOn: reportNoMetricActedOn } = useHealthFindingReporting(
+ !hasMetrics && isExperimentLaunched ? { code: 'no_metric' } : null
+ )
+
return (
<>
<ResultsNotificationBanner />
@@ -68,7 +74,12 @@ const MetricsTab = (): JSX.Element => {
{/* Modern metrics view */}
{!hasMetrics ? (
- <EmptyMetricsPanel isLaunched={isExperimentLaunched} />
+ <EmptyMetricsPanel
+ isLaunched={isExperimentLaunched}
+ onAddMetric={(metricType) =>
+ reportNoMetricActedOn(metricType === 'primary' ? 'add_primary_metric' : 'add_secondary_metric')
+ }
+ />
) : (
<>
<Metrics isSecondary={false} />
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentWarningBanners.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentWarningBanners.tsx
index dc708775c900..b948a63deb0c 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentWarningBanners.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentWarningBanners.tsx
@@ -9,6 +9,9 @@ import { urls } from 'scenes/urls'
import type { Experiment } from '~/types'
+import { healthFindingForExperimentWarning } from 'products/experiments/frontend/health/experimentHealthFindingEvents'
+import { useHealthFindingReporting } from 'products/experiments/frontend/health/useHealthFindingReporting'
+
import { experimentLogic } from '../experimentLogic'
import type { ExperimentWarning } from '../experimentLogic'
@@ -84,6 +87,9 @@ function WarningDetail({
export function ExperimentWarningBanner(): JSX.Element | null {
const { experimentWarning, experiment } = useValues(experimentLogic)
+ const { reportActedOn } = useHealthFindingReporting(
+ experimentWarning ? healthFindingForExperimentWarning(experimentWarning.key) : null
+ )
useEffect(() => {
if (experimentWarning) {
@@ -96,7 +102,11 @@ export function ExperimentWarningBanner(): JSX.Element | null {
}
const flagLink = experiment.feature_flag ? (
- <Link target="_blank" to={urls.featureFlag(experiment.feature_flag.id)}>
+ <Link
+ target="_blank"
+ to={urls.featureFlag(experiment.feature_flag.id)}
+ onClick={() => reportActedOn('open_feature_flag')}
+ >
{experiment.feature_flag.key}
</Link>
) : null
diff --git a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
index 1f742bceb059..2c13c57cb3bc 100644
--- a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
@@ -18,6 +18,8 @@ import { teamLogic } from 'scenes/teamLogic'
import { ExperimentExposureCriteria, ExperimentExposureQueryResponse } from '~/queries/schema/schema-general'
import { EXPERIMENT_VARIANT_MULTIPLE } from 'products/experiments/frontend/constants'
+import { getTotalExposures, hasSampleRatioMismatch } from 'products/experiments/frontend/health/exposureHealth'
+import { useHealthFindingReporting } from 'products/experiments/frontend/health/useHealthFindingReporting'
import { experimentLogic } from '../experimentLogic'
import { getActivationConfig, isDefaultExposureConfig } from '../exposureContract'
@@ -140,15 +142,10 @@ export function Exposures(): JSX.Element {
const exposuresElapsedSeconds = useElapsedSeconds(exposuresLoading)
const exposuresLoadingSlowly = exposuresLoading && exposuresElapsedSeconds >= SLOW_LOAD_THRESHOLD_SECONDS
- let totalExposures = 0
+ const totalExposures = getTotalExposures(exposures)
const variants: Array<{ variant: string; count: number; percentage: number }> = []
if (exposures?.timeseries) {
- for (const series of exposures.timeseries) {
- const count = exposures.total_exposures?.[series.variant] || 0
- totalExposures += Number(count)
- }
-
for (const series of exposures.timeseries) {
const count = exposures.total_exposures?.[series.variant] || 0
variants.push({
@@ -168,12 +165,31 @@ export function Exposures(): JSX.Element {
resolvedHandling === 'first_seen' ? 'using first seen variant' : 'excluded from analysis'
// Detect sample ratio mismatch (p < 0.001 is significant)
- const hasSRM = exposures?.sample_ratio_mismatch != null && exposures.sample_ratio_mismatch.p_value < 0.001
+ const hasSRM = hasSampleRatioMismatch(exposures)
- const handleCollapseChange = useCallback((activeKey: string | null) => {
- const isOpen = activeKey === 'cumulative-exposures'
- setIsCollapsed(!isOpen)
- }, [])
+ // The open panel says "No exposures yet" for a draft and after a failed exposure query too.
+ // Only a launched experiment with an answer that holds no exposure is the zero-exposure state.
+ const hasZeroExposures =
+ !isExperimentDraft && !exposuresLoading && exposures != null && !exposures.timeseries?.length
+
+ const { reportOpened: reportSrmOpened } = useHealthFindingReporting(
+ hasSRM && !isExperimentDraft && !exposuresLoading ? { code: 'srm' } : null
+ )
+ // The collapsed header shows the total only, so the zero-exposure state is on screen in the open panel alone.
+ const { reportOpened: reportZeroExposuresOpened, reportActedOn: reportZeroExposuresActedOn } =
+ useHealthFindingReporting(hasZeroExposures ? { code: 'zero_exposures' } : null, !isCollapsed)
+
+ const handleCollapseChange = useCallback(
+ (activeKey: string | null) => {
+ const isOpen = activeKey === 'cumulative-exposures'
+ setIsCollapsed(!isOpen)
+ if (isOpen) {
+ reportSrmOpened('evidence')
+ reportZeroExposuresOpened('evidence')
+ }
+ },
+ [reportSrmOpened, reportZeroExposuresOpened]
+ )
const headerContent = {
style: { backgroundColor: 'var(--color-bg-table)' },
@@ -301,7 +317,10 @@ export function Exposures(): JSX.Element {
size="xsmall"
className="flex items-center gap-2"
type="secondary"
- onClick={() => openExposureCriteriaModal(exposureCriteria)}
+ onClick={() => {
+ reportZeroExposuresActedOn('edit_exposure_criteria')
+ openExposureCriteriaModal(exposureCriteria)
+ }}
>
Edit exposure criteria
</LemonButton>
diff --git a/frontend/src/scenes/experiments/ExperimentView/MultiVariantBiasWarning.tsx b/frontend/src/scenes/experiments/ExperimentView/MultiVariantBiasWarning.tsx
index 4a0e0fe71ff9..7093ce71c9d5 100644
--- a/frontend/src/scenes/experiments/ExperimentView/MultiVariantBiasWarning.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/MultiVariantBiasWarning.tsx
@@ -6,6 +6,8 @@ import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'
import { getEventPropertiesForExperiment } from 'lib/utils/eventUsageLogic'
+import { useHealthFindingReporting } from 'products/experiments/frontend/health/useHealthFindingReporting'
+
import { experimentLogic } from '../experimentLogic'
import { modalsLogic } from '../modalsLogic'
import { exposureCriteriaModalLogic } from './exposureCriteriaModalLogic'
@@ -27,6 +29,9 @@ export function MultiVariantBiasWarning(): JSX.Element | null {
posthog.capture('experiment bias warning shown', { ...getEventPropertiesForExperiment(experiment) })
}
}, [risk, experiment])
+ const { reportOpened, reportActedOn } = useHealthFindingReporting(
+ risk ? { code: 'bias_risk_multiple_excluded' } : null
+ )
if (!risk) {
return null
@@ -49,6 +54,7 @@ export function MultiVariantBiasWarning(): JSX.Element | null {
<Link
to="https://posthog.com/docs/experiments/exposures#handling-multiple-exposures"
target="_blank"
+ onClick={() => reportOpened('docs')}
>
<strong>First seen</strong>
</Link>{' '}
@@ -56,18 +62,26 @@ export function MultiVariantBiasWarning(): JSX.Element | null {
</p>
</div>
<div className="flex gap-2 items-center flex-shrink-0">
- <LemonButton size="small" type="secondary" onClick={() => openDistributionModal()}>
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={() => {
+ reportActedOn('adjust_distribution')
+ openDistributionModal()
+ }}
+ >
Adjust distribution
</LemonButton>
<LemonButton
size="small"
type="secondary"
- onClick={() =>
+ onClick={() => {
+ reportActedOn('use_first_seen_variant')
openExposureCriteriaModal({
...exposureCriteria,
multiple_variant_handling: 'first_seen',
})
- }
+ }}
>
Use first seen variant
</LemonButton>
diff --git a/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx b/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx
new file mode 100644
index 000000000000..e5ac09f5bd7d
--- /dev/null
+++ b/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx
@@ -0,0 +1,144 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { BindLogic, Provider } from 'kea'
+import posthog from 'posthog-js'
+
+import { dayjs } from 'lib/dayjs'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { Experiment, ExperimentStatus } from '~/types'
+
+import { NEW_EXPERIMENT } from 'products/experiments/frontend/constants'
+
+import { experimentLogic } from '../experimentLogic'
+import { ExperimentWarningBanner } from './ExperimentWarningBanners'
+import { Exposures } from './Exposures'
+import { MultiVariantBiasWarning } from './MultiVariantBiasWarning'
+
+const EXPERIMENT_ID = 7
+
+const NO_EXPOSURES = { timeseries: [], total_exposures: {} }
+
+const UNEVEN_EXPOSURES = {
+ timeseries: [
+ { variant: 'control', days: ['2026-01-01', '2026-01-02'], exposure_counts: [300, 600] },
+ { variant: 'test', days: ['2026-01-01', '2026-01-02'], exposure_counts: [200, 400] },
+ ],
+ total_exposures: { control: 600, test: 400 },
+ sample_ratio_mismatch: { expected: { control: 500, test: 500 }, p_value: 0.0001 },
+ bias_risk: { multiple_variant_percentage: 5 },
+}
+
+describe('health finding reporting', () => {
+ let logic: ReturnType<typeof experimentLogic.build>
+ let captureSpy: jest.SpyInstance
+
+ const findingEvents = (): (string | undefined)[][] =>
+ captureSpy.mock.calls
+ .filter(([event]) => String(event).startsWith('experiment health finding'))
+ .map(([event, properties]) => [
+ event,
+ properties.finding_code,
+ properties.open_kind ?? properties.action_kind,
+ ])
+
+ // A running experiment whose flag is off, so the flag-state banner renders with its flag link.
+ const renderWarnings = (exposures: Record<string, unknown>): void => {
+ logic.actions.setExperiment({
+ ...NEW_EXPERIMENT,
+ id: EXPERIMENT_ID,
+ status: ExperimentStatus.Running,
+ start_date: dayjs().subtract(3, 'day').toISOString(),
+ feature_flag: { id: 1, key: 'checkout-flag', active: false, filters: { groups: [] } },
+ } as unknown as Experiment)
+ logic.actions.loadExposuresSuccess(exposures)
+ render(
+ <Provider>
+ <BindLogic logic={experimentLogic} props={{ experimentId: EXPERIMENT_ID }}>
+ <ExperimentWarningBanner />
+ <Exposures />
+ <MultiVariantBiasWarning />
+ </BindLogic>
+ </Provider>
+ )
+ }
+
+ beforeEach(() => {
+ const emptyList = { count: 0, next: null, previous: null, results: [] }
+ useMocks({
+ get: {
+ '/api/projects/:team/experiments': emptyList,
+ '/api/projects/:team/experiment_holdouts': emptyList,
+ '/api/projects/:team/experiment_saved_metrics': emptyList,
+ },
+ })
+ initKeaTests()
+ logic = experimentLogic({ experimentId: EXPERIMENT_ID })
+ logic.mount()
+ captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic.unmount()
+ })
+
+ it('reports each warning on screen as shown', () => {
+ renderWarnings(UNEVEN_EXPOSURES)
+
+ expect(findingEvents()).toEqual(
+ expect.arrayContaining([
+ ['experiment health finding shown', 'flag_off_while_running', undefined],
+ ['experiment health finding shown', 'srm', undefined],
+ ['experiment health finding shown', 'bias_risk_multiple_excluded', undefined],
+ ])
+ )
+ expect(findingEvents()).toHaveLength(3)
+ })
+
+ it.each([
+ {
+ control: 'Adjust distribution',
+ step: 'acted on',
+ code: 'bias_risk_multiple_excluded',
+ kind: 'adjust_distribution',
+ },
+ {
+ control: 'Use first seen variant',
+ step: 'acted on',
+ code: 'bias_risk_multiple_excluded',
+ kind: 'use_first_seen_variant',
+ },
+ { control: 'First seen', step: 'opened', code: 'bias_risk_multiple_excluded', kind: 'docs' },
+ { control: 'checkout-flag', step: 'acted on', code: 'flag_off_while_running', kind: 'open_feature_flag' },
+ { control: 'Exposures', step: 'opened', code: 'srm', kind: 'evidence' },
+ ])('reports $code as $step with $kind when a person uses "$control"', async ({ control, step, code, kind }) => {
+ renderWarnings(UNEVEN_EXPOSURES)
+ captureSpy.mockClear()
+
+ await userEvent.click(screen.getByText(control))
+
+ expect(findingEvents()).toEqual([[`experiment health finding ${step}`, code, kind]])
+ })
+
+ it('reports zero exposures only from the open panel, as shown and then as opened', async () => {
+ renderWarnings(NO_EXPOSURES)
+ expect(findingEvents()).toEqual([['experiment health finding shown', 'flag_off_while_running', undefined]])
+ captureSpy.mockClear()
+
+ await userEvent.click(screen.getByText('Exposures'))
+ expect(findingEvents()).toEqual([
+ ['experiment health finding shown', 'zero_exposures', undefined],
+ ['experiment health finding opened', 'zero_exposures', 'evidence'],
+ ])
+ captureSpy.mockClear()
+
+ await userEvent.click(screen.getByText('Edit exposure criteria'))
+ expect(findingEvents()).toEqual([
+ ['experiment health finding acted on', 'zero_exposures', 'edit_exposure_criteria'],
+ ])
+ })
+})
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 9a3d10a4a338..80391246731c 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -1,8 +1,10 @@
import { api } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { userLogic } from 'scenes/userLogic'
@@ -20,7 +22,9 @@ import {
NodeKind,
} from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import { Experiment, MultivariateFlagVariant } from '~/types'
+import { Experiment, ExperimentStatus, MultivariateFlagVariant } from '~/types'
+
+import type { ExperimentHealthFinding } from 'products/experiments/frontend/health/experimentHealthFindingEvents'
import { ExperimentWarning, experimentLogic } from './experimentLogic'
import type { ExperimentSavedMetric } from './utils'
@@ -357,6 +361,75 @@ describe('experimentLogic', () => {
})
}).toNotHaveDispatchedActions(['refreshExperimentResults'])
})
+
+ const unevenExposures = {
+ timeseries: [{ variant: 'control' }, { variant: 'test' }, { variant: '$multiple' }],
+ total_exposures: { control: 600, test: 350, $multiple: 50 },
+ sample_ratio_mismatch: { expected: { control: 475, test: 475 }, p_value: 0.0001 },
+ bias_risk: { multiple_variant_percentage: 5 },
+ }
+
+ it.each([
+ {
+ desc: 'no exposure answer',
+ exposures: null,
+ handling: undefined,
+ expected: { exposures_total: null, exposures_multiple: null, has_srm: null, has_bias_risk: null },
+ },
+ {
+ desc: 'an answer without exposures',
+ exposures: { timeseries: [], total_exposures: {} },
+ handling: undefined,
+ expected: { exposures_total: 0, exposures_multiple: 0, has_srm: false, has_bias_risk: false },
+ },
+ {
+ desc: 'an uneven split with users in several variants',
+ exposures: unevenExposures,
+ handling: 'exclude' as const,
+ expected: { exposures_total: 1000, exposures_multiple: 50, has_srm: true, has_bias_risk: true },
+ },
+ {
+ desc: 'first-seen handling, which hides the users in several variants',
+ exposures: {
+ timeseries: [{ variant: 'control' }, { variant: 'test' }],
+ total_exposures: { control: 600, test: 400 },
+ },
+ handling: 'first_seen' as const,
+ expected: { exposures_total: 1000, exposures_multiple: null, has_srm: false, has_bias_risk: false },
+ },
+ ])(
+ 'reports the exposure state with the completed refresh: $desc',
+ async ({ exposures, handling, expected }) => {
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ // The fixture holds legacy metrics, so the refresh keeps the exposures that are set here.
+ logic.actions.setExperiment({
+ ...experiment,
+ exposure_criteria: { ...experiment.exposure_criteria, multiple_variant_handling: handling },
+ })
+ if (exposures) {
+ logic.actions.loadExposuresSuccess(exposures)
+ }
+ useMocks({
+ post: {
+ '/api/environments/:team/query': () => [
+ 200,
+ { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },
+ ],
+ },
+ get: {
+ '/api/environments/:team/query/:id': () => [200, experimentMetricResultsSuccessJson],
+ },
+ })
+
+ await logic.asyncActions.refreshExperimentResults(true, 'manual')
+
+ const refreshEvents = captureSpy.mock.calls.filter(
+ ([event]) => event === 'experiment results refresh completed'
+ )
+ expect(refreshEvents).toHaveLength(1)
+ expect(refreshEvents[0][1]).toMatchObject(expected)
+ }
+ )
})
describe('updateExperimentMetrics', () => {
@@ -2536,6 +2609,105 @@ describe('experimentLogic', () => {
})
})
+ describe('health finding events', () => {
+ const findingEvents = (captureSpy: jest.SpyInstance): any[] =>
+ captureSpy.mock.calls
+ .filter(([event]) => String(event).startsWith('experiment health finding'))
+ .map(([event, properties]) => [event, properties])
+
+ it('reports a shown finding once per experiment load, without customer text', () => {
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ const draft = { ...experiment, id: 7, status: ExperimentStatus.Draft, start_date: undefined } as Experiment
+ const finding: ExperimentHealthFinding = {
+ code: 'flag_live_before_launch',
+ variant: 'not_started_but_multiple_variants_rolled_out',
+ }
+
+ logic.actions.loadExperimentSuccess(draft)
+ logic.actions.reportHealthFindingShown(finding)
+ logic.actions.reportHealthFindingShown(finding)
+
+ expect(findingEvents(captureSpy)).toEqual([
+ [
+ 'experiment health finding shown',
+ {
+ experiment_id: 7,
+ experiment_status: 'draft',
+ experiment_days_since_start: null,
+ finding_code: 'flag_live_before_launch',
+ finding_variant: 'not_started_but_multiple_variants_rolled_out',
+ surface: 'experiment_page',
+ source: 'web',
+ },
+ ],
+ ])
+
+ logic.actions.loadExperimentSuccess(draft)
+ logic.actions.reportHealthFindingShown(finding)
+
+ expect(findingEvents(captureSpy)).toHaveLength(2)
+ })
+
+ it('reports every use of a finding action', () => {
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ logic.actions.setExperiment({
+ ...experiment,
+ id: 7,
+ status: ExperimentStatus.Running,
+ start_date: dayjs().subtract(3, 'day').toISOString(),
+ })
+
+ logic.actions.reportHealthFindingActedOn({ code: 'bias_risk_multiple_excluded' }, 'use_first_seen_variant')
+ logic.actions.reportHealthFindingActedOn({ code: 'bias_risk_multiple_excluded' }, 'use_first_seen_variant')
+
+ expect(findingEvents(captureSpy)).toEqual(
+ Array(2).fill([
+ 'experiment health finding acted on',
+ {
+ experiment_id: 7,
+ experiment_status: 'running',
+ experiment_days_since_start: 3,
+ finding_code: 'bias_risk_multiple_excluded',
+ finding_variant: null,
+ surface: 'experiment_page',
+ source: 'web',
+ action_kind: 'use_first_seen_variant',
+ action_step: 'started',
+ },
+ ])
+ )
+ })
+
+ it('reports a finding as shown before it reports the finding as opened', () => {
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ const running = {
+ ...experiment,
+ id: 7,
+ status: ExperimentStatus.Running,
+ start_date: dayjs().subtract(3, 'day').toISOString(),
+ }
+ const properties = {
+ experiment_id: 7,
+ experiment_status: 'running',
+ experiment_days_since_start: 3,
+ finding_code: 'zero_exposures',
+ finding_variant: null,
+ surface: 'experiment_page',
+ source: 'web',
+ }
+
+ logic.actions.loadExperimentSuccess(running)
+ logic.actions.reportHealthFindingOpened({ code: 'zero_exposures' }, 'evidence')
+ logic.actions.reportHealthFindingOpened({ code: 'zero_exposures' }, 'evidence')
+
+ expect(findingEvents(captureSpy)).toEqual([
+ ['experiment health finding shown', properties],
+ ['experiment health finding opened', { ...properties, open_kind: 'evidence' }],
+ ['experiment health finding opened', { ...properties, open_kind: 'evidence' }],
+ ])
+ })
+ })
+
describe('excluded variants', () => {
it('excludedVariants selector reads the excluded_variants column', async () => {
await expectLogic(logic, () => {
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 9946e747a3dc..a3d84a8e892b 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -83,6 +83,15 @@ import {
MetricInsightId,
} from 'products/experiments/frontend/constants'
import { hasEnded, isLaunched } from 'products/experiments/frontend/experimentStatus'
+import {
+ type ExperimentHealthFinding,
+ type ExperimentHealthFindingActionKind,
+ type ExperimentHealthFindingOpenKind,
+ captureExperimentHealthFindingActedOn,
+ captureExperimentHealthFindingOpened,
+ captureExperimentHealthFindingShown,
+ exposureHealthEventProperties,
+} from 'products/experiments/frontend/health/experimentHealthFindingEvents'
import {
legacyExpectedRunningTime,
legacyMinimumSampleSizePerVariant,
@@ -450,6 +459,7 @@ export interface experimentLogicValues {
excludedVariants: string[]
experiment: Experiment
experimentId: Experiment['id']
+ experimentLoadCount: number
experimentLoading: boolean
experimentMissing: boolean
experimentUpdate: Experiment | null
@@ -903,6 +913,23 @@ export interface experimentLogicActions {
experiment: Experiment
forceRefresh: boolean
}
+ reportHealthFindingActedOn: (
+ finding: ExperimentHealthFinding,
+ actionKind: ExperimentHealthFindingActionKind
+ ) => {
+ actionKind: ExperimentHealthFindingActionKind
+ finding: ExperimentHealthFinding
+ }
+ reportHealthFindingOpened: (
+ finding: ExperimentHealthFinding,
+ openKind: ExperimentHealthFindingOpenKind
+ ) => {
+ finding: ExperimentHealthFinding
+ openKind: ExperimentHealthFindingOpenKind
+ }
+ reportHealthFindingShown: (finding: ExperimentHealthFinding) => {
+ finding: ExperimentHealthFinding
+ }
resetRunningExperiment: () => {
value: true
}
@@ -1342,6 +1369,15 @@ export const experimentLogic = kea<experimentLogicType>([
previous_refresh_triggered_by?: string | null
}
) => ({ experiment, forceRefresh, context }),
+ reportHealthFindingShown: (finding: ExperimentHealthFinding) => ({ finding }),
+ reportHealthFindingOpened: (finding: ExperimentHealthFinding, openKind: ExperimentHealthFindingOpenKind) => ({
+ finding,
+ openKind,
+ }),
+ reportHealthFindingActedOn: (
+ finding: ExperimentHealthFinding,
+ actionKind: ExperimentHealthFindingActionKind
+ ) => ({ finding, actionKind }),
setExperimentMissing: true,
setExperiment: (experiment: Partial<Experiment>) => ({ experiment }),
setLaunchExperimentLoading: (loading: boolean) => ({ loading }),
@@ -1579,6 +1615,15 @@ export const experimentLogic = kea<experimentLogicType>([
toggleDebugPanel: (state) => !state,
},
],
+ // A health finding is reported at most once per load, the unit of `experiment viewed`. A load
+ // without the finding's event does not mean that the finding is gone: only the flag-state
+ // banner renders on every tab. `experiment results refresh completed` holds the state per load.
+ experimentLoadCount: [
+ 0,
+ {
+ loadExperimentSuccess: (state) => state + 1,
+ },
+ ],
currentRefresh: [
null as CurrentRefreshSnapshot | null,
{
@@ -2201,6 +2246,26 @@ export const experimentLogic = kea<experimentLogicType>([
previous_refresh_triggered_by: context?.previous_refresh_triggered_by ?? null,
})
},
+ reportHealthFindingShown: ({ finding }) => {
+ // The page remounts its warnings within one load, for example on a tab change or after
+ // a save, and each mount reports again.
+ const key = `${values.experimentLoadCount}:${finding.code}:${finding.variant ?? ''}`
+ cache.shownHealthFindingKeys ??= new Set<string>()
+ if (cache.shownHealthFindingKeys.has(key)) {
+ return
+ }
+ cache.shownHealthFindingKeys.add(key)
+ captureExperimentHealthFindingShown(values.experiment, finding)
+ },
+ reportHealthFindingOpened: ({ finding, openKind }) => {
+ // Zero exposures has no sign in the collapsed panel, so the reader opens it before the
+ // page reports it. Report "shown" first to keep the order of the two events.
+ actions.reportHealthFindingShown(finding)
+ captureExperimentHealthFindingOpened(values.experiment, finding, openKind)
+ },
+ reportHealthFindingActedOn: ({ finding, actionKind }) => {
+ captureExperimentHealthFindingActedOn(values.experiment, finding, actionKind)
+ },
beforeUnmount: () => {
clearTimeout(cache.notificationOfferTimer)
},
@@ -2515,6 +2580,10 @@ export const experimentLogic = kea<experimentLogicType>([
experiment_status: values.experiment?.status ?? null,
total_metrics_count: primaryCount + secondaryCount,
execution_mode: getExperimentExecutionMode(values.featureFlags),
+ ...exposureHealthEventProperties(
+ values.exposures,
+ values.exposureCriteria?.multiple_variant_handling
+ ),
})
const finalState: FinishedRefreshState = caughtError
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index eeb4ead8d3a8..903f7895764a 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -137,6 +137,8 @@ class CleanupRequestSummary(TypedDict):
DEFAULT_ROLLOUT_PERCENTAGE = 100
ExperimentCreationMode = Literal["new", "duplicate", "copy_to_project"]
+# The launch action is not the only way to launch. A create call or an update that sets the start date launches too.
+ExperimentLaunchPath = Literal["launch_endpoint", "create_request", "update_start_date"]
def _parse_tag_names(value: Any) -> list[str]:
@@ -1266,6 +1268,13 @@ class ExperimentService:
creation_mode=creation_mode,
analytics_properties=analytics_properties,
)
+ if experiment.start_date is not None:
+ self._report_experiment_launched(
+ experiment,
+ launch_path="create_request",
+ request=serializer_context.get("request") if serializer_context else None,
+ event_source=event_source,
+ )
except Exception:
logger.exception("experiment_created_analytics_failed", experiment_id=experiment.id)
@@ -1280,17 +1289,21 @@ class ExperimentService:
*,
request: Any | None,
extra_metadata: dict[str, Any] | None = None,
+ event_source: EventSource | None = None,
) -> None:
"""Emit a lifecycle analytics event with the experiment's standard metadata.
- No-ops for non-HTTP callers (``request`` is None). ``report_user_action`` is referenced as a
- module-level name so tests can patch it at this module's path.
+ No-ops for a caller that has neither a ``request`` nor an ``event_source``.
+ ``report_user_action`` is referenced as a module-level name so tests can patch it at this
+ module's path.
"""
- if request is None:
+ if request is None and event_source is None:
return
metadata = experiment.get_analytics_metadata()
if extra_metadata:
metadata.update(extra_metadata)
+ if event_source is not None:
+ metadata["source"] = event_source
report_user_action(self.user, event_name, metadata, team=experiment.team, request=request)
def _report_experiment_created(
@@ -1330,14 +1343,26 @@ class ExperimentService:
self,
experiment: Experiment,
*,
+ launch_path: ExperimentLaunchPath,
request: Any | None = None,
+ event_source: EventSource | None = None,
) -> None:
- self._report_lifecycle_event(
- experiment,
- "experiment launched",
- request=request,
- extra_metadata={"launch_date": experiment.start_date.isoformat() if experiment.start_date else None},
- )
+ # Every path saves the launch before it reports it, so an analytics failure must not fail the request.
+ try:
+ flag_age = timezone.now() - experiment.feature_flag.created_at
+ self._report_lifecycle_event(
+ experiment,
+ "experiment launched",
+ request=request,
+ event_source=event_source,
+ extra_metadata={
+ "launch_date": experiment.start_date.isoformat() if experiment.start_date else None,
+ "launch_path": launch_path,
+ "flag_age_seconds": int(flag_age.total_seconds()),
+ },
+ )
+ except Exception:
+ logger.exception("experiment_launched_analytics_failed", experiment_id=experiment.id)
def _ensure_feature_flag(
self,
@@ -1749,7 +1774,7 @@ class ExperimentService:
]
)
- self._report_experiment_launched(experiment, request=request)
+ self._report_experiment_launched(experiment, launch_path="launch_endpoint", request=request)
return experiment
@@ -3633,6 +3658,14 @@ class ExperimentService:
deprecated_config_changed=deprecated_flag_config_changed,
)
+ if launching:
+ self._report_experiment_launched(
+ experiment,
+ launch_path="update_start_date",
+ request=report_request,
+ event_source=event_source,
+ )
+
return experiment
def _sync_feature_flag_on_update(
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 4852d425d559..2cbdf498948a 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -8,6 +8,7 @@ from typing import Any
from uuid import UUID, uuid4
import pytest
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, PropertyMock, patch
@@ -2793,6 +2794,12 @@ class TestExperimentService(APIBaseTest):
kwargs.setdefault("allow_unknown_events", True)
return self._service().create_experiment(name=name, feature_flag_key=feature_flag_key, **kwargs)
+ def _create_launchable_experiment_on_flag_of_age(self, age: timedelta, **kwargs: Any) -> Experiment:
+ experiment = self._create_launchable_experiment(**kwargs)
+ FeatureFlag.objects.filter(pk=experiment.feature_flag_id).update(created_at=timezone.now() - age)
+ experiment.feature_flag.refresh_from_db()
+ return experiment
+
def _create_ended_experiment(
self,
name: str = "Ended",
@@ -3790,6 +3797,103 @@ class TestExperimentService(APIBaseTest):
mock_report_user_action.assert_called_once()
assert mock_report_user_action.call_args.args[1] == event_name
+ @parameterized.expand(
+ [
+ (
+ "launch_endpoint",
+ lambda self: self._create_launchable_experiment(name="Path L", feature_flag_key="path-launch-flag"),
+ lambda service, experiment, request: service.launch_experiment(experiment, request=request),
+ [("launch_endpoint", 0)],
+ ),
+ (
+ "launch_endpoint_on_older_flag",
+ lambda self: self._create_launchable_experiment_on_flag_of_age(
+ timedelta(days=3, hours=2), name="Path O", feature_flag_key="path-older-flag"
+ ),
+ lambda service, experiment, request: service.launch_experiment(experiment, request=request),
+ [("launch_endpoint", 266400)],
+ ),
+ (
+ "create_with_start_date",
+ lambda self: None,
+ lambda service, experiment, request: service.create_experiment(
+ name="Path C",
+ feature_flag_key="path-create-flag",
+ start_date=timezone.now(),
+ event_source=EventSource.API,
+ ),
+ [("create_request", 0)],
+ ),
+ (
+ "create_draft",
+ lambda self: None,
+ lambda service, experiment, request: service.create_experiment(
+ name="Path D", feature_flag_key="path-draft-flag", event_source=EventSource.API
+ ),
+ [],
+ ),
+ (
+ "update_sets_start_date_on_draft",
+ lambda self: self._create_launchable_experiment(name="Path U", feature_flag_key="path-update-flag"),
+ lambda service, experiment, request: service.update_experiment(
+ experiment, {"start_date": timezone.now()}, event_source=EventSource.API
+ ),
+ [("update_start_date", 0)],
+ ),
+ (
+ "update_moves_start_date_of_running",
+ lambda self: self._create_running_experiment(name="Path M", feature_flag_key="path-move-flag"),
+ lambda service, experiment, request: service.update_experiment(
+ experiment, {"start_date": timezone.now() - timedelta(days=1)}, event_source=EventSource.API
+ ),
+ [],
+ ),
+ ]
+ )
+ @patch("products.experiments.backend.experiment_service.report_user_action")
+ def test_experiment_launched_reported_once_per_launch(self, _name, build, act, expected, mock_report_user_action):
+ with time_machine.travel(timezone.now(), tick=False):
+ experiment = build(self)
+ mock_report_user_action.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ act(self._service(), experiment, self._make_request())
+
+ launched = [
+ call.args[2] for call in mock_report_user_action.call_args_list if call.args[1] == "experiment launched"
+ ]
+ assert [(event["launch_path"], event["flag_age_seconds"]) for event in launched] == expected
+
+ @parameterized.expand(
+ [
+ (
+ "launch_endpoint",
+ lambda service, experiment, request: service.launch_experiment(experiment, request=request),
+ ),
+ (
+ "update_sets_start_date_on_draft",
+ lambda service, experiment, request: service.update_experiment(
+ experiment, {"start_date": timezone.now()}, event_source=EventSource.API
+ ),
+ ),
+ ]
+ )
+ def test_launch_is_saved_when_its_report_fails(self, _name, act):
+ def fail_launch_report(_user: Any, event: str, *_args: Any, **_kwargs: Any) -> None:
+ if event == "experiment launched":
+ raise RuntimeError("capture failed")
+
+ experiment = self._create_launchable_experiment(name="Path F", feature_flag_key="path-failed-report-flag")
+
+ with patch(
+ "products.experiments.backend.experiment_service.report_user_action", side_effect=fail_launch_report
+ ) as mock_report_user_action:
+ act(self._service(), experiment, self._make_request())
+
+ assert "experiment launched" in [call.args[1] for call in mock_report_user_action.call_args_list]
+ experiment.refresh_from_db()
+ assert experiment.start_date is not None
+
# ------------------------------------------------------------------
# Freeze exposure
# ------------------------------------------------------------------
diff --git a/products/experiments/frontend/health/experimentHealthFindingEvents.ts b/products/experiments/frontend/health/experimentHealthFindingEvents.ts
new file mode 100644
index 000000000000..736bf0ed2696
--- /dev/null
+++ b/products/experiments/frontend/health/experimentHealthFindingEvents.ts
@@ -0,0 +1,130 @@
+import { dayjs } from 'lib/dayjs'
+import posthog from 'lib/posthog-typed'
+import type { ExperimentWarningKey } from 'scenes/experiments/experimentLogic'
+
+import type { ExperimentExposureCriteria, ExperimentExposureQueryResponse } from '~/queries/schema/schema-general'
+import type { Experiment } from '~/types'
+
+import { EXPERIMENT_VARIANT_MULTIPLE } from '../constants'
+import { getExperimentStatus } from '../experimentStatus'
+import { getTotalExposures, hasSampleRatioMismatch } from './exposureHealth'
+
+// pinned: `finding_code` property values. Insights group and filter on them, so a rename breaks those insights.
+export type ExperimentHealthFindingCode =
+ | 'flag_off_while_running'
+ | 'variant_shipped_while_running'
+ | 'flag_live_after_end'
+ | 'flag_live_before_launch'
+ | 'bias_risk_multiple_excluded'
+ | 'srm'
+ | 'zero_exposures'
+ | 'no_metric'
+
+export interface ExperimentHealthFinding {
+ code: ExperimentHealthFindingCode
+ /** The sub-case of the code, for example the warning key. It must not hold customer text. */
+ variant?: string
+}
+
+// pinned: `open_kind` property values, for the same reason as the codes above.
+export type ExperimentHealthFindingOpenKind = 'evidence' | 'docs'
+
+// pinned: `action_kind` property values, for the same reason as the codes above.
+export type ExperimentHealthFindingActionKind =
+ | 'adjust_distribution'
+ | 'use_first_seen_variant'
+ | 'open_feature_flag'
+ | 'edit_exposure_criteria'
+ | 'add_primary_metric'
+ | 'add_secondary_metric'
+
+const EXPERIMENT_WARNING_FINDING_CODES: Record<ExperimentWarningKey, ExperimentHealthFindingCode> = {
+ running_but_flag_disabled: 'flag_off_while_running',
+ running_but_no_rollout: 'flag_off_while_running',
+ running_but_single_variant_shipped: 'variant_shipped_while_running',
+ ended_but_multiple_variants_rolled_out: 'flag_live_after_end',
+ not_started_but_multiple_variants_rolled_out: 'flag_live_before_launch',
+}
+
+export function healthFindingForExperimentWarning(warningKey: ExperimentWarningKey): ExperimentHealthFinding {
+ return { code: EXPERIMENT_WARNING_FINDING_CODES[warningKey], variant: warningKey }
+}
+
+// These events are read in aggregate, so they carry ids, codes and counts only. The experiment
+// name, the flag key and the metric definitions are customer text, so do not spread
+// `getEventPropertiesForExperiment` in.
+function healthFindingEventProperties(
+ experiment: Experiment,
+ finding: ExperimentHealthFinding
+): Record<string, string | number | null> {
+ return {
+ experiment_id: experiment.id,
+ experiment_status: getExperimentStatus(experiment),
+ experiment_days_since_start: experiment.start_date ? dayjs().diff(experiment.start_date, 'day') : null,
+ finding_code: finding.code,
+ finding_variant: finding.variant ?? null,
+ surface: 'experiment_page',
+ // The value the backend reports for a request from the web app, so one breakdown covers both.
+ source: 'web',
+ }
+}
+
+export function captureExperimentHealthFindingShown(experiment: Experiment, finding: ExperimentHealthFinding): void {
+ // pinned: analytics event name, so renaming it breaks insights
+ posthog.capture('experiment health finding shown', healthFindingEventProperties(experiment, finding))
+}
+
+export function captureExperimentHealthFindingOpened(
+ experiment: Experiment,
+ finding: ExperimentHealthFinding,
+ openKind: ExperimentHealthFindingOpenKind
+): void {
+ // pinned: analytics event name, so renaming it breaks insights
+ posthog.capture('experiment health finding opened', {
+ ...healthFindingEventProperties(experiment, finding),
+ open_kind: openKind,
+ })
+}
+
+export function captureExperimentHealthFindingActedOn(
+ experiment: Experiment,
+ finding: ExperimentHealthFinding,
+ actionKind: ExperimentHealthFindingActionKind
+): void {
+ // pinned: analytics event name, so renaming it breaks insights
+ posthog.capture('experiment health finding acted on', {
+ ...healthFindingEventProperties(experiment, finding),
+ action_kind: actionKind,
+ // A click starts the action. The save that completes it happens in a modal or on another page.
+ action_step: 'started',
+ })
+}
+
+/**
+ * The exposure warnings render on one tab only, so a "shown" event cannot give the exposure state of
+ * every load. `experiment results refresh completed` follows the exposure load on every tab.
+ */
+export function exposureHealthEventProperties(
+ exposures: ExperimentExposureQueryResponse | null | undefined,
+ multipleVariantHandling: ExperimentExposureCriteria['multiple_variant_handling']
+): {
+ exposures_total: number | null
+ exposures_multiple: number | null
+ has_srm: boolean | null
+ has_bias_risk: boolean | null
+} {
+ if (!exposures) {
+ return { exposures_total: null, exposures_multiple: null, has_srm: null, has_bias_risk: null }
+ }
+ return {
+ exposures_total: getTotalExposures(exposures),
+ // With "first seen" handling the exposure query gives each person their first variant and
+ // counts no `$multiple`, so the number of people in several variants is unknown there.
+ exposures_multiple:
+ multipleVariantHandling === 'first_seen'
+ ? null
+ : Number(exposures.total_exposures?.[EXPERIMENT_VARIANT_MULTIPLE] || 0),
+ has_srm: hasSampleRatioMismatch(exposures),
+ has_bias_risk: exposures.bias_risk != null,
+ }
+}
diff --git a/products/experiments/frontend/health/exposureHealth.ts b/products/experiments/frontend/health/exposureHealth.ts
new file mode 100644
index 000000000000..8c110aa23dd2
--- /dev/null
+++ b/products/experiments/frontend/health/exposureHealth.ts
@@ -0,0 +1,18 @@
+import type { ExperimentExposureQueryResponse } from '~/queries/schema/schema-general'
+
+const SAMPLE_RATIO_MISMATCH_P_VALUE = 0.001
+
+export function hasSampleRatioMismatch(exposures: ExperimentExposureQueryResponse | null | undefined): boolean {
+ return (
+ exposures?.sample_ratio_mismatch != null &&
+ exposures.sample_ratio_mismatch.p_value < SAMPLE_RATIO_MISMATCH_P_VALUE
+ )
+}
+
+/** The exposed users of every variant in the exposure answer, the `$multiple` variant included. */
+export function getTotalExposures(exposures: ExperimentExposureQueryResponse | null | undefined): number {
+ return (exposures?.timeseries ?? []).reduce(
+ (total, series) => total + Number(exposures?.total_exposures?.[series.variant] || 0),
+ 0
+ )
+}
diff --git a/products/experiments/frontend/health/useHealthFindingReporting.ts b/products/experiments/frontend/health/useHealthFindingReporting.ts
new file mode 100644
index 000000000000..eb882192ec08
--- /dev/null
+++ b/products/experiments/frontend/health/useHealthFindingReporting.ts
@@ -0,0 +1,57 @@
+import { useActions, useValues } from 'kea'
+import { useCallback, useEffect } from 'react'
+
+import { experimentLogic } from 'scenes/experiments/experimentLogic'
+
+import type {
+ ExperimentHealthFinding,
+ ExperimentHealthFindingActionKind,
+ ExperimentHealthFindingOpenKind,
+} from './experimentHealthFindingEvents'
+
+export interface HealthFindingReporters {
+ reportOpened: (openKind: ExperimentHealthFindingOpenKind) => void
+ reportActedOn: (actionKind: ExperimentHealthFindingActionKind) => void
+}
+
+/**
+ * Reports a finding of the experiment while the caller has it on screen, and returns the reporters
+ * for a reader's use of it. Pass null while the experiment has no such finding: the reporters then
+ * do nothing. Pass `isShown` as false while the finding exists and the caller shows no sign of it.
+ */
+export function useHealthFindingReporting(
+ finding: ExperimentHealthFinding | null,
+ isShown: boolean = true
+): HealthFindingReporters {
+ const { experimentLoadCount } = useValues(experimentLogic)
+ const { reportHealthFindingShown, reportHealthFindingOpened, reportHealthFindingActedOn } =
+ useActions(experimentLogic)
+ const code = finding?.code
+ const variant = finding?.variant
+
+ useEffect(() => {
+ if (code && isShown) {
+ reportHealthFindingShown({ code, variant })
+ }
+ }, [code, variant, isShown, experimentLoadCount, reportHealthFindingShown])
+
+ const reportOpened = useCallback(
+ (openKind: ExperimentHealthFindingOpenKind): void => {
+ if (code) {
+ reportHealthFindingOpened({ code, variant }, openKind)
+ }
+ },
+ [code, variant, reportHealthFindingOpened]
+ )
+
+ const reportActedOn = useCallback(
+ (actionKind: ExperimentHealthFindingActionKind): void => {
+ if (code) {
+ reportHealthFindingActedOn({ code, variant }, actionKind)
+ }
+ },
+ [code, variant, reportHealthFindingActedOn]
+ )
+
+ return { reportOpened, reportActedOn }
+}
diff --git a/products/experiments/frontend/scenes/experimentsLogic.test.ts b/products/experiments/frontend/scenes/experimentsLogic.test.ts
index e59996fb0b5d..4da7ae1cad93 100644
--- a/products/experiments/frontend/scenes/experimentsLogic.test.ts
+++ b/products/experiments/frontend/scenes/experimentsLogic.test.ts
@@ -330,6 +330,40 @@ describe('experimentsLogic', () => {
expect(logic.values.experiments.results).toEqual([freshExperiment])
})
+ it.each([
+ {
+ desc: 'a first view',
+ filters: { status: 'all' as const, page: 1, archived: false },
+ expected: { statusFilter: 'all', page: 1, hasSearch: false, archived: false },
+ },
+ {
+ desc: 'a later page of a search in the archive',
+ filters: { status: ExperimentStatus.Running, page: 2, search: 'checkout', archived: true },
+ expected: { statusFilter: ExperimentStatus.Running, page: 2, hasSearch: true, archived: true },
+ },
+ ])(
+ 'reports a list view with the filters of the request that answered: $desc',
+ async ({ filters, expected }) => {
+ await expectLogic(logic, () => {
+ logic.actions.loadExperimentsSuccess({
+ results: [mockExperiment, mockRunningExperiment],
+ count: 2,
+ filters,
+ })
+ }).toDispatchActions([
+ logic.actionCreators.reportExperimentsListViewed({ experimentsShown: 2, ...expected }),
+ ])
+ }
+ )
+
+ it('reports no list view when the list loads behind another tab', async () => {
+ logic.actions.setExperimentsTab(ExperimentsTabs.SharedMetrics)
+
+ await expectLogic(logic, () => {
+ logic.actions.loadExperimentsSuccess({ results: [mockExperiment, mockRunningExperiment], count: 2 })
+ }).toNotHaveDispatchedActions(['reportExperimentsListViewed'])
+ })
+
it('constructs correct params from filters', () => {
logic.actions.setExperimentsFilters({
search: 'test',
diff --git a/products/experiments/frontend/scenes/experimentsLogic.ts b/products/experiments/frontend/scenes/experimentsLogic.ts
index 9f67172e055d..545070bcd7ea 100644
--- a/products/experiments/frontend/scenes/experimentsLogic.ts
+++ b/products/experiments/frontend/scenes/experimentsLogic.ts
@@ -6,6 +6,7 @@ import { LemonTagType, PaginationManual } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { parseNumericArrayFilter, parseTagsFilter, toParams } from 'lib/utils/url'
import { getFlagVariants } from 'scenes/experiments/utils'
import { FLAGS_PER_PAGE, type FeatureFlagsResult, featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
@@ -194,6 +195,19 @@ export interface experimentsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentsLogicActions {
+ reportExperimentsListViewed: (listView: {
+ archived: boolean
+ experimentsShown: number
+ hasSearch: boolean
+ page: number
+ statusFilter: string
+ }) => {
+ archived: boolean
+ experimentsShown: number
+ hasSearch: boolean
+ page: number
+ statusFilter: string
+ } // eventUsageLogic
loadCurrentTeamSuccess: (
currentTeam: TeamPublicType | null,
payload?: any
@@ -536,7 +550,12 @@ export const experimentsLogic = kea<experimentsLogicType>([
teamLogic,
['currentTeam'],
],
- actions: [teamLogic, ['loadCurrentTeamSuccess', 'updateCurrentTeamSuccess']],
+ actions: [
+ teamLogic,
+ ['loadCurrentTeamSuccess', 'updateCurrentTeamSuccess'],
+ eventUsageLogic,
+ ['reportExperimentsListViewed'],
+ ],
})),
actions({
setExperimentsTab: (tabKey: ExperimentsTabs) => ({ tabKey }),
@@ -601,6 +620,19 @@ export const experimentsLogic = kea<experimentsLogicType>([
resetFeatureFlagModalFilters: () => {
actions.loadFeatureFlagModalFeatureFlags()
},
+ loadExperimentsSuccess: ({ experiments }) => {
+ // The list also loads behind the other tabs of the scene, where nobody sees it.
+ if (values.tab === ExperimentsTabs.All) {
+ const filters = experiments.filters ?? {}
+ actions.reportExperimentsListViewed({
+ experimentsShown: experiments.results.length,
+ statusFilter: filters.status ?? 'all',
+ page: filters.page ?? 1,
+ hasSearch: !!filters.search,
+ archived: !!filters.archived,
+ })
+ }
+ },
loadCurrentTeamSuccess: () => {
if (values.featureFlagModalFeatureFlags.results.length > 0) {
actions.loadFeatureFlagModalFeatureFlags()
@@ -617,6 +649,8 @@ export const experimentsLogic = kea<experimentsLogicType>([
{ results: [], count: 0, filters: DEFAULT_FILTERS, offset: 0 } as ExperimentsResult,
{
loadExperiments: async (_: void, breakpoint) => {
+ // A filter change during the request must not relabel this response.
+ const filters = values.filters
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use experimentsList() from 'products/experiments/frontend/generated/api' instead.
const response = await api.get(
`api/projects/${values.currentProjectId}/experiments?${toParams(values.paramsFromFilters)}`
@@ -626,6 +660,7 @@ export const experimentsLogic = kea<experimentsLogicType>([
return {
...response,
offset: values.paramsFromFilters.offset,
+ filters,
}
},
archiveExperiment: async ({ id, disableFeatureFlag }: { id: number; disableFeatureFlag: boolean }) => {