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): show more info on health panel and move to tab (#118399)

Marcel Poelker78838358c230
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7534e68a3f96..54df97329c56 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10562,6 +10562,10 @@ snapshots:
hash: v1.k794b7964.fd72f35bde6794c88bdbb1bd65de9526006c3e83e4785cb0d25d630352661b89.69Wlq5LtvYFbYyR5sTUoLICbigisjrec9IH0fgrXdmA
scenes-app-experiments--experiment-frequentist-two-variants--light:
hash: v1.k794b7964.4ddea1c7537af9d50c57b4b9a76d4bcba39f743a23b4715683c0ce59d4c24f57.0ueR8XMLqRby_u6I0EyNIiUwXkbjmWMH3vBdoFNYmII
+ scenes-app-experiments--experiment-health-debug-tab--dark:
+ hash: v1.k794b7964.da80c2341c1d9168fa6162308de4aff94d1f925de89e45617d40d984626fff77.kyN0nKYMyjL1PI6j0UGQnzhfI_sW0no-H2DnrHBcW10
+ scenes-app-experiments--experiment-health-debug-tab--light:
+ hash: v1.k794b7964.564e4d31874244bc07e7c7cbcb22c3f63cce8d67e3c0d3e719b2e6f46b0d6c43.Px3OMagE9Nd2lyonNDffZ1wuQg94IwFpXFNd0hYR_YE
scenes-app-experiments--experiment-recordings-dropped-metric--dark:
hash: v1.k794b7964.e0e7181f2c9e61a8324eff9aa7a9230fef25b3cf37e0b24ef875780186ed25dc.9VEvZ4iVieVJwmDol0gwtAsr3wgZYW5gj2KXAGZJfiw
scenes-app-experiments--experiment-recordings-dropped-metric--light:
@@ -10683,9 +10687,9 @@ snapshots:
scenes-app-experiments--experiment-with-funnel-metric--light:
hash: v1.k794b7964.bb7e2defaafa4f1741e8da0eeba2700055a382088f7592d51bc7afe34a119aca.FI-i_7oS0vyvJQTgk_AmwDHgSn2Yq46yhWw-2X4uMMI
scenes-app-experiments--experiment-with-health-findings--dark:
- hash: v1.k794b7964.bf3245d485cdf4423f638c7d0f4f6a6cbd7b9973a714b6d97754f9d759f9db52.u8I1lVXq8xvgY0M_lVcDOsb9SfALFXkvgsVLUAIE0ww
+ hash: v1.k794b7964.5444bb7f0d8c52bc6b999f76b8161b75b681eb0ca4226ed33ee4ac2af91def97.5RJqZf1qeIelyQZVdfLqcqGBEwjO34GgcFiPLViCikI
scenes-app-experiments--experiment-with-health-findings--light:
- hash: v1.k794b7964.04d7f04f53aeb6ca300aacdf85f342f63ac09efafd0aff92b67d1c8e4d6bc6b5.4nAbtk7eJ-PGKzdL8yAHskpYkI_nBHEtYh0-ZFWKNI4
+ hash: v1.k794b7964.93009a5a6f5936341f3f4d80200d2f7ff348643723927344cdcdee3a9766c734.K_mpvll3tb6dM6xQNRGYhRPcUBp0sP_4ZjjOZuhZ5-M
scenes-app-experiments--experiment-with-long-flag-key--dark:
hash: v1.k794b7964.3fbbef4f86a4d189e4bb3787512ec428e16efe1d529f7f19526a634a876abda3.cYQ-vlh6PsxZDQg2g5KTlLjzUJO0_rxE3oyGtXXJbpM
scenes-app-experiments--experiment-with-long-flag-key--light:
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx
index 167b6086cb99..9098c1bbb97f 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx
@@ -10,7 +10,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { ActivityScope } from '~/types'
import { ExperimentMetaBar } from 'products/experiments/frontend/components/ExperimentMetaBar'
-import { ExperimentHealthDebug } from 'products/experiments/frontend/health/ExperimentHealthDebug'
+import { ExperimentHealthDebug } from 'products/experiments/frontend/health/debug/ExperimentHealthDebug'
import { ExperimentHealthPanel } from 'products/experiments/frontend/health/ExperimentHealthPanel'
import { useHealthFindingReporting } from 'products/experiments/frontend/health/useHealthFindingReporting'
import { LegacyExperimentView } from 'products/experiments/frontend/legacy/LegacyExperimentView'
@@ -154,9 +154,9 @@ export function ExperimentView(): JSX.Element {
}
// Ordered as: results (Metrics), configuration (Settings, Code, Variants),
- // feature tabs (Recordings, User feedback), audit trail (History). Which of these actually
- // render is resolved by experimentSceneLogic's availableTabs, so the tab set, the URL, and the
- // tracked tab stay in agreement.
+ // feature tabs (Recordings, User feedback), audit trail (History), staff debugging (Health debug).
+ // Which of these actually render is resolved by experimentSceneLogic's availableTabs, so the tab set,
+ // the URL, and the tracked tab stay in agreement.
const tabs: LemonTab<ExperimentTab>[] = (
[
{ key: 'metrics', label: 'Metrics', content: <MetricsTab /> },
@@ -170,6 +170,7 @@ export function ExperimentView(): JSX.Element {
label: 'History',
content: <ActivityLog scope={ActivityScope.EXPERIMENT} id={experimentId} />,
},
+ { key: 'health-debug', label: 'Health debug', content: <ExperimentHealthDebug /> },
] satisfies LemonTab<ExperimentTab>[]
).filter((tab) => availableTabs.includes(tab.key))
@@ -197,7 +198,6 @@ export function ExperimentView(): JSX.Element {
)}
<ExperimentMetaBar />
<ExperimentHealthPanel />
- <ExperimentHealthDebug />
<ExperimentHeader />
<LemonTabs
// Fall back to the default tab if the active one is conditionally hidden
diff --git a/frontend/src/scenes/experiments/experimentSceneLogic.test.ts b/frontend/src/scenes/experiments/experimentSceneLogic.test.ts
index 1e179e5c256c..37c7afb8ea32 100644
--- a/frontend/src/scenes/experiments/experimentSceneLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentSceneLogic.test.ts
@@ -9,7 +9,12 @@ import { initKeaTests } from '~/test/init'
import { Experiment } from '~/types'
import { FORM_MODES } from './experimentLogic'
-import { DEFAULT_EXPERIMENT_TAB, experimentSceneLogic, getAvailableExperimentTabs } from './experimentSceneLogic'
+import {
+ DEFAULT_EXPERIMENT_TAB,
+ canSeeHealthDebugTab,
+ experimentSceneLogic,
+ getAvailableExperimentTabs,
+} from './experimentSceneLogic'
const LEGACY_EXPERIMENT = {
id: 123,
@@ -274,6 +279,34 @@ describe('experimentSceneLogic', () => {
const withFlag = { ...DRAFT_EXPERIMENT, feature_flag: { id: 1 } } as Experiment
expect(getAvailableExperimentTabs(withFlag).includes('feedback')).toBe(true)
})
+
+ it.each([
+ [
+ 'staff with the flag',
+ { superpowersEnabled: true, isImpersonated: false, healthFindingsEnabled: true },
+ true,
+ ],
+ [
+ 'staff impersonating',
+ { superpowersEnabled: false, isImpersonated: true, healthFindingsEnabled: true },
+ true,
+ ],
+ [
+ 'staff without the flag',
+ { superpowersEnabled: true, isImpersonated: true, healthFindingsEnabled: false },
+ false,
+ ],
+ [
+ 'a customer with the flag',
+ { superpowersEnabled: false, isImpersonated: false, healthFindingsEnabled: true },
+ false,
+ ],
+ ])('offers the health debug tab to %s: %s', (_label, gate, expected) => {
+ const tabs = getAvailableExperimentTabs(LAUNCHED_EXPERIMENT, {
+ canSeeHealthDebug: canSeeHealthDebugTab(gate),
+ })
+ expect(tabs.includes('health-debug')).toBe(expected)
+ })
})
it('clamps the active tab to the default once the experiment loads without it', async () => {
diff --git a/frontend/src/scenes/experiments/experimentSceneLogic.tsx b/frontend/src/scenes/experiments/experimentSceneLogic.tsx
index c31ef763cfdd..20c29e9d162c 100644
--- a/frontend/src/scenes/experiments/experimentSceneLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentSceneLogic.tsx
@@ -2,6 +2,7 @@ import {
MakeLogicType,
BuiltLogic,
actions,
+ connect,
kea,
listeners,
path,
@@ -15,13 +16,17 @@ import { router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
+import { superpowersLogic } from 'lib/components/Superpowers/superpowersLogic'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
-import { ActivityScope, Breadcrumb, Experiment, ProjectTreeRef } from '~/types'
+import { ActivityScope, Breadcrumb, Experiment, ProjectTreeRef, type UserType } from '~/types'
import type { ExperimentIdType } from '~/types'
import { NEW_EXPERIMENT } from 'products/experiments/frontend/constants'
@@ -46,14 +51,26 @@ function reportExperimentTabViewed(experimentId: ExperimentIdType, tab: string):
})
}
-export const EXPERIMENT_TABS = ['metrics', 'settings', 'code', 'variants', 'recordings', 'feedback', 'history'] as const
+export const EXPERIMENT_TABS = [
+ 'metrics',
+ 'settings',
+ 'code',
+ 'variants',
+ 'recordings',
+ 'feedback',
+ 'history',
+ 'health-debug',
+] as const
export type ExperimentTab = (typeof EXPERIMENT_TABS)[number]
export const DEFAULT_EXPERIMENT_TAB: ExperimentTab = 'metrics'
// The single source of truth for which tabs an experiment renders, shared by the views and by the
// scene logic that clamps the URL-driven tab. Keep it in sync with the tab lists in ExperimentView
// and LegacyExperimentView — a tab the views render but this omits gets clamped away on load.
-export const getAvailableExperimentTabs = (experiment: Experiment): ExperimentTab[] => {
+export const getAvailableExperimentTabs = (
+ experiment: Experiment,
+ { canSeeHealthDebug = false }: { canSeeHealthDebug?: boolean } = {}
+): ExperimentTab[] => {
// Legacy experiments render a reduced, read-only view with only these two tabs.
if (isLegacyExperiment(experiment)) {
return ['metrics', 'variants']
@@ -66,12 +83,26 @@ export const getAvailableExperimentTabs = (experiment: Experiment): ExperimentTa
return !isDraft
case 'feedback':
return !!experiment.feature_flag
+ case 'health-debug':
+ return canSeeHealthDebug
default:
return true
}
})
}
+// Staff only. While impersonating, the user is the customer, so superpowers are off for the staff member at the
+// keyboard and the impersonation itself counts.
+export const canSeeHealthDebugTab = ({
+ superpowersEnabled,
+ isImpersonated,
+ healthFindingsEnabled,
+}: {
+ superpowersEnabled: boolean
+ isImpersonated: boolean
+ healthFindingsEnabled: boolean
+}): boolean => (superpowersEnabled || isImpersonated) && healthFindingsEnabled
+
// kea-router coerces numeric-looking params to numbers, so check the type before membership
const isExperimentTab = (tab: unknown): tab is ExperimentTab =>
typeof tab === 'string' && (EXPERIMENT_TABS as readonly string[]).includes(tab)
@@ -106,9 +137,13 @@ export interface ExperimentSceneLogicProps extends ExperimentLogicProps {}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface experimentSceneLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ superpowersEnabled: boolean | undefined // superpowersLogic
+ user: UserType | null // userLogic
activeTabKey: ExperimentTab
availableTabs: ExperimentTab[]
breadcrumbs: Breadcrumb[]
+ canSeeHealthDebug: boolean
experiment: Experiment
experimentId: ExperimentIdType
experimentLoaded: boolean
@@ -133,7 +168,15 @@ export interface experimentSceneLogicActions {
experimentConfig: Experiment
}
setActiveTabKey: (activeTabKey: ExperimentTab) => {
- activeTabKey: 'code' | 'feedback' | 'history' | 'metrics' | 'recordings' | 'settings' | 'variants'
+ activeTabKey:
+ | 'code'
+ | 'feedback'
+ | 'health-debug'
+ | 'history'
+ | 'metrics'
+ | 'recordings'
+ | 'settings'
+ | 'variants'
}
setEditMode: (editing: boolean) => {
editing: boolean
@@ -194,7 +237,12 @@ export interface experimentSceneLogicMeta {
} | null
) => ((state: any, props?: ExperimentLogicProps | undefined) => boolean) | undefined
isExperimentLaunched: (arg: boolean | undefined) => boolean
- availableTabs: (experiment: Experiment) => ExperimentTab[]
+ canSeeHealthDebug: (
+ superpowersEnabled: boolean | undefined,
+ user: UserType | null,
+ featureFlags: FeatureFlagsSet
+ ) => boolean
+ availableTabs: (experiment: Experiment, canSeeHealthDebug: boolean) => ExperimentTab[]
experimentLoaded: (experiment: Experiment) => boolean
breadcrumbs: (experiment: Experiment, experimentId: ExperimentIdType) => Breadcrumb[]
sidePanelContext: (experimentId: ExperimentIdType) => SidePanelSceneContext | null
@@ -212,6 +260,9 @@ export type experimentSceneLogicType = MakeLogicType<
export const experimentSceneLogic = kea<experimentSceneLogicType>([
props({} as ExperimentSceneLogicProps),
path(['scenes', 'experiments', 'experimentSceneLogic']),
+ connect(() => ({
+ values: [superpowersLogic, ['superpowersEnabled'], featureFlagLogic, ['featureFlags'], userLogic, ['user']],
+ })),
actions({
setActiveTabKey: (activeTabKey: ExperimentTab) => ({ activeTabKey }),
setSceneState: (experimentId: Experiment['id'], formMode: FormModes) => ({ experimentId, formMode }),
@@ -327,9 +378,19 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([
],
(isExperimentLaunched: boolean | undefined): boolean => isExperimentLaunched ?? false,
],
+ canSeeHealthDebug: [
+ (s) => [s.superpowersEnabled, s.user, s.featureFlags],
+ (superpowersEnabled: boolean | undefined, user: UserType | null, featureFlags: FeatureFlagsSet): boolean =>
+ canSeeHealthDebugTab({
+ superpowersEnabled: !!superpowersEnabled,
+ isImpersonated: !!user?.is_impersonated,
+ healthFindingsEnabled: !!featureFlags[FEATURE_FLAGS.EXPERIMENT_HEALTH_FINDINGS],
+ }),
+ ],
availableTabs: [
- (s) => [s.experiment],
- (experiment: Experiment): ExperimentTab[] => getAvailableExperimentTabs(experiment),
+ (s) => [s.experiment, s.canSeeHealthDebug],
+ (experiment: Experiment, canSeeHealthDebug: boolean): ExperimentTab[] =>
+ getAvailableExperimentTabs(experiment, { canSeeHealthDebug }),
],
experimentLoaded: [
(s) => [s.experiment],
diff --git a/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx
new file mode 100644
index 000000000000..e4517869939a
--- /dev/null
+++ b/frontend/src/scenes/experiments/stories/ExperimentHealthDebugTab.stories.tsx
@@ -0,0 +1,151 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+import EXPERIMENT_WITH_MEAN_METRIC from '~/mocks/fixtures/api/experiments/experiment_with_mean_metric.json'
+import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_query_result.json'
+import MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/mean_metric_result.json'
+import { NodeKind } from '~/queries/schema/schema-general'
+
+import type { ExperimentHealthInputsApi } from 'products/experiments/frontend/generated/api.schemas'
+
+import { recalculationMocks, resultsByMetricType } from './recalculationMocks'
+
+const SPLIT_BEFORE = [
+ { key: 'control', rollout_percentage: 50 },
+ { key: 'test-1', rollout_percentage: 25 },
+ { key: 'test-2', rollout_percentage: 25 },
+]
+const SPLIT_AFTER = [
+ { key: 'control', rollout_percentage: 34 },
+ { key: 'test-1', rollout_percentage: 33 },
+ { key: 'test-2', rollout_percentage: 33 },
+]
+
+const EXPERIMENT_HEALTH = {
+ findings: [
+ {
+ code: 'split_changed_mid_run',
+ subcode: 'rebalanced',
+ severity: 'warning',
+ title: 'The variant split changed after launch',
+ detail: '',
+ evidence: {
+ change_count: 1,
+ from: 'January 20, 2025',
+ to: 'January 20, 2025',
+ exposed_before_change: true,
+ },
+ actions: ['open_feature_flag'],
+ diagnostic_ref: 'E3',
+ },
+ ],
+}
+
+// Typed as the generated response, so a new required field on the serializer breaks the typecheck here.
+const HEALTH_INPUTS: ExperimentHealthInputsApi = {
+ is_launched: true,
+ is_running: true,
+ has_ended: false,
+ is_paused: false,
+ archived: false,
+ baseline_variant_key: null,
+ excluded_variant_keys: [],
+ primary_metric_count: 1,
+ secondary_metric_count: 0,
+ flag: {
+ active: true,
+ deleted: false,
+ release_conditions: [
+ { number: 1, rollout_percentage: 100, property_count: 1, reachable: true, pinned_variant: 'test-1' },
+ { number: 2, rollout_percentage: 100, property_count: 0, reachable: true, pinned_variant: null },
+ ],
+ variants: SPLIT_AFTER,
+ },
+ split_history: {
+ checked: true,
+ not_checked_reason: null,
+ launched_at: '2025-01-06T10:00:00Z',
+ team_timezone: 'UTC',
+ changes: [{ changed_at: '2025-01-20T14:30:00Z', before: SPLIT_BEFORE, after: SPLIT_AFTER, counted: true }],
+ exposed_before_first: true,
+ exposed_between: null,
+ },
+ condition_set_traffic_status: 'read',
+ condition_set_traffic: {
+ since: '2025-01-20T14:30:00Z',
+ team_timezone: 'UTC',
+ people_by_set: [
+ { condition_set: 1, people: 12 },
+ { condition_set: 2, people: 2988 },
+ ],
+ calls: 4200,
+ remotely_evaluated_calls: 4116,
+ },
+ reader_access: { can_read_flag_history: true, can_query_events: true, denied_event_properties: [] },
+ exposures: {
+ status: 'ready',
+ computed_at: '2025-01-27T06:00:00Z',
+ totals: {
+ total_exposures: { control: 989, 'test-1': 874, 'test-2': 1137 },
+ multiple_variant_handling: 'exclude',
+ sample_ratio_mismatch_p_value: 0.31,
+ hours_since_launch: 500,
+ },
+ findings: [],
+ error: null,
+ },
+ project: {
+ team_defaults: { status: 'skipped', data: null },
+ sdk_profile: { status: 'skipped', data: null },
+ },
+}
+
+const RECALCULATION = recalculationMocks(
+ EXPERIMENT_WITH_MEAN_METRIC,
+ resultsByMetricType(EXPERIMENT_WITH_MEAN_METRIC, { mean: MEAN_METRIC_RESULT })
+)
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/Experiments',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2025-01-27',
+ pageUrl: `${urls.experiment(EXPERIMENT_WITH_MEAN_METRIC.id)}?tab=health-debug`,
+ featureFlags: [FEATURE_FLAGS.EXPERIMENT_HEALTH_FINDINGS],
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ ...RECALCULATION.get,
+ [`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MEAN_METRIC.id}/`]: EXPERIMENT_WITH_MEAN_METRIC,
+ [`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MEAN_METRIC.id}/health/`]: EXPERIMENT_HEALTH,
+ [`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MEAN_METRIC.id}/health_inputs/`]: HEALTH_INPUTS,
+ [`/api/projects/:team_id/experiment_holdouts`]: [],
+ [`/api/projects/:team_id/experiment_saved_metrics/`]: [],
+ [`/api/projects/:team_id/feature_flags/${EXPERIMENT_WITH_MEAN_METRIC.feature_flag.id}/`]: {},
+ [`/api/projects/:team_id/feature_flags/${EXPERIMENT_WITH_MEAN_METRIC.feature_flag.id}/status/`]: {},
+ [`/api/environments/:team_id/default_release_conditions/`]: [],
+ },
+ post: {
+ ...RECALCULATION.post,
+ // Exposures still load through experimentLogic; metric results come from the recalculation run.
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ return body.query.kind === NodeKind.ExperimentExposureQuery ? [200, EXPOSURE_QUERY_RESULT] : [404]
+ },
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+// Staff only: the tab shows for staff with the health findings flag, so superpowers come from the debug preflight.
+export const ExperimentHealthDebugTab: Story = {}
diff --git a/products/experiments/frontend/health/ExperimentHealthDebug.tsx b/products/experiments/frontend/health/ExperimentHealthDebug.tsx
deleted file mode 100644
index acff2d1c6fc9..000000000000
--- a/products/experiments/frontend/health/ExperimentHealthDebug.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useValues } from 'kea'
-
-import { LemonCollapse, LemonTag } from '@posthog/lemon-ui'
-
-import { superpowersLogic } from 'lib/components/Superpowers/superpowersLogic'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-
-import { HealthDebugTables } from './HealthDebugTables'
-
-export function ExperimentHealthDebug(): JSX.Element | null {
- const { superpowersEnabled } = useValues(superpowersLogic)
- const { featureFlags } = useValues(featureFlagLogic)
-
- if (!superpowersEnabled || !featureFlags[FEATURE_FLAGS.EXPERIMENT_HEALTH_FINDINGS]) {
- return null
- }
-
- return (
- <LemonCollapse
- panels={[
- {
- key: 'health-debug',
- header: (
- <span className="flex items-center gap-2">
- Health checks debug
- <LemonTag type="muted">Staff only</LemonTag>
- </span>
- ),
- dataAttr: 'experiment-health-debug',
- content: <HealthDebugTables />,
- },
- ]}
- />
- )
-}
diff --git a/products/experiments/frontend/health/HealthDebugTables.tsx b/products/experiments/frontend/health/HealthDebugTables.tsx
deleted file mode 100644
index 4f6a322a1da8..000000000000
--- a/products/experiments/frontend/health/HealthDebugTables.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { useValues } from 'kea'
-
-import { LemonTable, LemonTag } from '@posthog/lemon-ui'
-
-import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
-import { experimentLogic } from 'scenes/experiments/experimentLogic'
-
-import { experimentHealthDebugLogic } from './experimentHealthDebugLogic'
-import type { HealthDebugCheck, HealthDebugFact } from './healthDebugReport'
-
-export function HealthDebugTables(): JSX.Element {
- const { experimentHealth, experimentId, healthFindings } = useValues(experimentLogic)
- const { healthDebugChecks: checks, healthDebugFacts: facts } = useValues(
- experimentHealthDebugLogic({ experimentId })
- )
-
- return (
- <div className="flex flex-col gap-4">
- <LemonTable<HealthDebugFact>
- size="small"
- showHeader={false}
- dataSource={facts}
- rowKey="label"
- columns={[
- { key: 'label', render: (_, fact) => <span className="font-semibold">{fact.label}</span> },
- { key: 'value', render: (_, fact) => <span className="font-mono text-xs">{fact.value}</span> },
- ]}
- />
- <LemonTable<HealthDebugCheck>
- size="small"
- dataSource={checks}
- rowKey={(check) => `${check.check}:${check.source}`}
- columns={[
- { title: 'Check', key: 'check', render: (_, check) => <code>{check.check}</code> },
- { title: 'Source', dataIndex: 'source' },
- {
- title: 'Result',
- key: 'result',
- render: (_, check) => (
- <span className="flex items-center gap-2">
- <code>{check.result}</code>
- {check.differs && <LemonTag type="danger">Differs</LemonTag>}
- </span>
- ),
- },
- { title: 'Inputs', dataIndex: 'note' },
- ]}
- />
- <CodeSnippet language={Language.JSON} thing="health debug data" maxLinesWithoutExpansion={12}>
- {JSON.stringify({ health: experimentHealth, panelFindings: healthFindings, checks, facts }, null, 2)}
- </CodeSnippet>
- </div>
- )
-}
diff --git a/products/experiments/frontend/health/debug/ExperimentHealthDebug.tsx b/products/experiments/frontend/health/debug/ExperimentHealthDebug.tsx
new file mode 100644
index 000000000000..b9f8a404a48a
--- /dev/null
+++ b/products/experiments/frontend/health/debug/ExperimentHealthDebug.tsx
@@ -0,0 +1,95 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh } from '@posthog/icons'
+import { LemonButton, LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'
+
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+import { experimentLogic } from 'scenes/experiments/experimentLogic'
+
+import { SetupFactsTable } from '../../setupInspector/SetupFactsTable'
+import { experimentHealthDebugLogic } from './experimentHealthDebugLogic'
+import { HealthDebugCheckResults } from './HealthDebugCheckResults'
+import { HealthDebugFlagTab } from './HealthDebugFlagTab'
+import { HealthDebugProjectTab } from './HealthDebugProjectTab'
+import { HEALTH_DEBUG_DOMAIN_LABELS, type HealthDebugDomain } from './healthDebugReport'
+import { HealthDebugSection } from './HealthDebugSection'
+
+const DOMAINS: HealthDebugDomain[] = ['experiment', 'flag', 'exposures', 'metrics', 'project', 'raw']
+
+/** The staff-only experiment tab: what each health check concluded, and the inputs it read, by domain. */
+export function ExperimentHealthDebug(): JSX.Element {
+ const { experimentId } = useValues(experimentLogic)
+ const logic = experimentHealthDebugLogic({ experimentId })
+ const {
+ activeDomain,
+ healthDebugSummary,
+ experimentFacts,
+ metricFacts,
+ exposureFacts,
+ healthDebugRawData,
+ healthInputsLoading,
+ } = useValues(logic)
+ const { setActiveDomain, loadHealthInputs } = useActions(logic)
+
+ const domainContent: Record<HealthDebugDomain, JSX.Element> = {
+ experiment: <SetupFactsTable facts={experimentFacts} />,
+ flag: <HealthDebugFlagTab />,
+ exposures: (
+ <div className="flex flex-col gap-2">
+ <p className="text-secondary text-sm mb-0">
+ The exposure query's cached answer that the zero-exposures, SRM and bias checks read on the server.
+ </p>
+ <SetupFactsTable facts={exposureFacts} />
+ </div>
+ ),
+ metrics: <SetupFactsTable facts={metricFacts} />,
+ project: <HealthDebugProjectTab />,
+ raw: (
+ <CodeSnippet language={Language.JSON} thing="health debug data" maxLinesWithoutExpansion={20}>
+ {JSON.stringify(healthDebugRawData, null, 2)}
+ </CodeSnippet>
+ ),
+ }
+
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div className="flex flex-col gap-1">
+ <h3 className="flex items-center gap-2 mb-0">
+ Health checks debug
+ <LemonTag type="muted">Staff only</LemonTag>
+ </h3>
+ <p className="text-secondary text-sm mb-0">
+ What each health check concluded, and the inputs it read. Customers don't see this tab.
+ </p>
+ </div>
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconRefresh />}
+ loading={healthInputsLoading}
+ onClick={() => loadHealthInputs()}
+ data-attr="experiment-health-debug-reload"
+ >
+ Reload inputs
+ </LemonButton>
+ </div>
+ <SetupFactsTable facts={healthDebugSummary} />
+ <HealthDebugSection
+ title="Check results"
+ description="One row per check. The buttons under Reads open the inputs the check reads."
+ >
+ <HealthDebugCheckResults />
+ </HealthDebugSection>
+ <HealthDebugSection title="Inputs" description="The values the checks read, grouped by domain.">
+ <LemonSegmentedButton
+ size="small"
+ value={activeDomain}
+ onChange={setActiveDomain}
+ options={DOMAINS.map((domain) => ({ value: domain, label: HEALTH_DEBUG_DOMAIN_LABELS[domain] }))}
+ />
+ {domainContent[activeDomain]}
+ </HealthDebugSection>
+ </div>
+ )
+}
diff --git a/products/experiments/frontend/health/debug/HealthDebugCheckResults.tsx b/products/experiments/frontend/health/debug/HealthDebugCheckResults.tsx
new file mode 100644
index 000000000000..c3749e93a2f5
--- /dev/null
+++ b/products/experiments/frontend/health/debug/HealthDebugCheckResults.tsx
@@ -0,0 +1,101 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonTable, LemonTag, type LemonTagType, Tooltip } from '@posthog/lemon-ui'
+
+import { experimentLogic } from 'scenes/experiments/experimentLogic'
+
+import { formatTimestamp } from '../../setupInspector/setupInspectorUtils'
+import { experimentHealthDebugLogic } from './experimentHealthDebugLogic'
+import { HEALTH_DEBUG_DOMAIN_LABELS, type HealthDebugCheck } from './healthDebugReport'
+
+const SEVERITY_TAG_TYPES: Record<NonNullable<HealthDebugCheck['severity']>, LemonTagType> = {
+ critical: 'danger',
+ warning: 'warning',
+ info: 'muted',
+}
+
+function ComputedAt({ timestamp }: { timestamp: string }): JSX.Element {
+ return (
+ <span className="text-xs text-secondary" translate="no">
+ computed {formatTimestamp(timestamp)}
+ </span>
+ )
+}
+
+export function HealthDebugCheckResults(): JSX.Element {
+ const { experimentId } = useValues(experimentLogic)
+ const { healthDebugChecks } = useValues(experimentHealthDebugLogic({ experimentId }))
+ const { setActiveDomain } = useActions(experimentHealthDebugLogic({ experimentId }))
+
+ return (
+ <LemonTable<HealthDebugCheck>
+ size="small"
+ dataSource={healthDebugChecks}
+ rowKey="check"
+ columns={[
+ {
+ title: 'Check',
+ key: 'check',
+ render: (_, check) => (
+ <div className="flex flex-col">
+ <code translate="no">{check.check}</code>
+ <span className="text-secondary text-xs">from the {check.source}</span>
+ </div>
+ ),
+ },
+ {
+ title: 'Result',
+ key: 'result',
+ render: (_, check) => (
+ <div className="flex flex-col gap-1">
+ <span className="flex flex-wrap items-center gap-1">
+ {check.severity && (
+ <LemonTag type={SEVERITY_TAG_TYPES[check.severity]}>{check.severity}</LemonTag>
+ )}
+ <code translate="no">{check.result}</code>
+ {check.computedAt && <ComputedAt timestamp={check.computedAt} />}
+ </span>
+ {check.browser !== null && (
+ <span className="flex flex-wrap items-center gap-1 text-xs text-secondary">
+ <span>{check.browserLabel}:</span>
+ <code translate="no">{check.browser}</code>
+ {check.browserComputedAt && <ComputedAt timestamp={check.browserComputedAt} />}
+ {check.difference === 'disagrees' && <LemonTag type="danger">Differs</LemonTag>}
+ {check.difference === 'drift' && (
+ <Tooltip title="The page's exposure answer is cached apart from the server's and computed at another time, so the two can differ. The panel shows the page's.">
+ <LemonTag type="muted">Drift</LemonTag>
+ </Tooltip>
+ )}
+ </span>
+ )}
+ </div>
+ ),
+ },
+ {
+ title: 'Reads',
+ key: 'reads',
+ render: (_, check) => (
+ <div className="flex flex-wrap gap-1 min-w-44">
+ {check.reads.map((domain) => (
+ <LemonButton
+ key={domain}
+ size="xsmall"
+ type="secondary"
+ onClick={() => setActiveDomain(domain)}
+ data-attr="experiment-health-debug-reads"
+ >
+ {HEALTH_DEBUG_DOMAIN_LABELS[domain]}
+ </LemonButton>
+ ))}
+ </div>
+ ),
+ },
+ {
+ title: 'Details',
+ key: 'note',
+ render: (_, check) => <span className="text-xs">{check.note}</span>,
+ },
+ ]}
+ />
+ )
+}
diff --git a/products/experiments/frontend/health/debug/HealthDebugFlagTab.tsx b/products/experiments/frontend/health/debug/HealthDebugFlagTab.tsx
new file mode 100644
index 000000000000..526eab66f9c5
--- /dev/null
+++ b/products/experiments/frontend/health/debug/HealthDebugFlagTab.tsx
@@ -0,0 +1,122 @@
+import { useValues } from 'kea'
+
+import { LemonBanner, LemonTable } from '@posthog/lemon-ui'
+
+import { experimentLogic } from 'scenes/experiments/experimentLogic'
+
+import { SetupFactsTable } from '../../setupInspector/SetupFactsTable'
+import { formatCount, formatYesNo } from '../../setupInspector/setupInspectorUtils'
+import { experimentHealthDebugLogic } from './experimentHealthDebugLogic'
+import type { HealthDebugReleaseCondition, HealthDebugSplitChange } from './healthDebugInputs'
+import { HealthDebugSection } from './HealthDebugSection'
+
+export function HealthDebugFlagTab(): JSX.Element {
+ const { experimentId } = useValues(experimentLogic)
+ const {
+ flagFacts,
+ releaseConditions,
+ splitHistoryFacts,
+ splitChanges,
+ trafficFacts,
+ healthInputs,
+ healthInputsLoading,
+ healthInputsError,
+ } = useValues(experimentHealthDebugLogic({ experimentId }))
+ const trafficRead = !!healthInputs?.condition_set_traffic
+ const splitHistoryChecked = !!healthInputs?.split_history?.checked
+
+ return (
+ <div className="flex flex-col gap-4">
+ {healthInputsError && <LemonBanner type="error">{healthInputsError}</LemonBanner>}
+ <HealthDebugSection
+ title="Configuration"
+ description="The flag as the health checks read it on the server."
+ >
+ <SetupFactsTable facts={flagFacts} />
+ <LemonTable<HealthDebugReleaseCondition>
+ size="small"
+ loading={healthInputsLoading}
+ dataSource={releaseConditions}
+ rowKey="number"
+ emptyState="No release conditions."
+ columns={[
+ { title: 'Set', key: 'number', render: (_, condition) => condition.number },
+ {
+ title: 'Rollout',
+ key: 'rollout',
+ align: 'right',
+ render: (_, condition) =>
+ condition.rolloutPercentage === null ? 'Unset' : `${condition.rolloutPercentage}%`,
+ },
+ {
+ title: 'Properties',
+ key: 'properties',
+ align: 'right',
+ render: (_, condition) => condition.propertyCount ?? 'Unknown',
+ },
+ {
+ title: 'Reachable',
+ key: 'reachable',
+ render: (_, condition) => formatYesNo(condition.reachable),
+ },
+ {
+ title: 'Pinned variant',
+ key: 'pinned',
+ render: (_, condition) =>
+ condition.pinnedVariant ? (
+ <code translate="no">{condition.pinnedVariant}</code>
+ ) : (
+ <span className="text-secondary">None</span>
+ ),
+ },
+ ...(trafficRead
+ ? [
+ {
+ title: 'People in the window',
+ key: 'people',
+ align: 'right' as const,
+ render: (_: unknown, condition: HealthDebugReleaseCondition) =>
+ formatCount(condition.people),
+ },
+ ]
+ : []),
+ ]}
+ />
+ </HealthDebugSection>
+ <HealthDebugSection
+ title="Split changes since launch"
+ description="What the split-change check read from the flag's history."
+ >
+ <SetupFactsTable facts={splitHistoryFacts} />
+ {splitChanges.length > 0 && (
+ <LemonTable<HealthDebugSplitChange>
+ size="small"
+ dataSource={splitChanges}
+ rowKey={(change, index) => `${change.changedAt}-${index}`}
+ columns={[
+ { title: 'Changed at', dataIndex: 'changedAt' },
+ { title: 'Before', dataIndex: 'before' },
+ { title: 'After', dataIndex: 'after' },
+ ...(splitHistoryChecked
+ ? [
+ {
+ title: 'Counts',
+ key: 'counted',
+ render: (_: unknown, change: HealthDebugSplitChange) =>
+ formatYesNo(change.counted),
+ },
+ ]
+ : []),
+ ]}
+ />
+ )}
+ </HealthDebugSection>
+ <HealthDebugSection
+ title="Calls by release condition"
+ description="The flag's recent calls that the forced-variant check grades pinned conditions by."
+ >
+ <SetupFactsTable facts={trafficFacts} />
+ </HealthDebugSection>
+ </div>
+ )
+}
diff --git a/products/experiments/frontend/health/debug/HealthDebugProjectTab.tsx b/products/experiments/frontend/health/debug/HealthDebugProjectTab.tsx
new file mode 100644
index 000000000000..8e09455baacc
--- /dev/null
+++ b/products/experiments/frontend/health/debug/HealthDebugProjectTab.tsx
@@ -0,0 +1,35 @@
+import { useValues } from 'kea'
+
+import { LemonSkeleton } from '@posthog/lemon-ui'
+
+import { experimentLogic } from 'scenes/experiments/experimentLogic'
+
+import { SdkProfileSection } from '../../setupInspector/sections/SdkProfileSection'
+import { TeamDefaultsSection } from '../../setupInspector/sections/TeamDefaultsSection'
+import { experimentHealthDebugLogic } from './experimentHealthDebugLogic'
+
+export function HealthDebugProjectTab(): JSX.Element {
+ const { experimentId } = useValues(experimentLogic)
+ const { healthInputs, healthInputsLoading } = useValues(experimentHealthDebugLogic({ experimentId }))
+
+ if (!healthInputs) {
+ return healthInputsLoading ? (
+ <LemonSkeleton repeat={6} className="h-6" />
+ ) : (
+ <p className="text-secondary mb-0">The project facts did not load. Reload the inputs to try again.</p>
+ )
+ }
+ return (
+ <div className="flex flex-col gap-4">
+ <p className="text-secondary text-sm mb-0">
+ Project-wide facts, read by the same providers as the setup context. No check reads them yet. They help
+ explain a finding, for example when flags are evaluated outside the flag service.
+ </p>
+ <SdkProfileSection
+ section={healthInputs.project.sdk_profile}
+ skippedMessage="Skipped, because you may not query events or are denied a property it reads."
+ />
+ <TeamDefaultsSection section={healthInputs.project.team_defaults} />
+ </div>
+ )
+}
diff --git a/products/experiments/frontend/health/debug/HealthDebugSection.tsx b/products/experiments/frontend/health/debug/HealthDebugSection.tsx
new file mode 100644
index 000000000000..358c801b4fee
--- /dev/null
+++ b/products/experiments/frontend/health/debug/HealthDebugSection.tsx
@@ -0,0 +1,15 @@
+export interface HealthDebugSectionProps {
+ title: string
+ description?: string
+ children: React.ReactNode
+}
+
+export function HealthDebugSection({ title, description, children }: HealthDebugSectionProps): JSX.Element {
+ return (
+ <section className="flex flex-col gap-2">
+ <h4 className="mb-0">{title}</h4>
+ {description && <p className="text-secondary text-sm mb-0">{description}</p>}
+ {children}
+ </section>
+ )
+}
diff --git a/products/experiments/frontend/health/debug/experimentHealthDebugLogic.ts b/products/experiments/frontend/health/debug/experimentHealthDebugLogic.ts
new file mode 100644
index 000000000000..263ae12208df
--- /dev/null
+++ b/products/experiments/frontend/health/debug/experimentHealthDebugLogic.ts
@@ -0,0 +1,363 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import {
+ type ExperimentLogicProps,
+ type ExperimentWarning,
+ experimentLogic,
+ getSectionMetricUuids,
+} from 'scenes/experiments/experimentLogic'
+import { projectLogic } from 'scenes/projectLogic'
+
+import type { Experiment, ExperimentIdType } from '~/types'
+
+import { experimentsHealthInputsRetrieve } from '../../generated/api'
+import type { ExperimentHealthApi, ExperimentHealthInputsApi } from '../../generated/api.schemas'
+import type { SetupFact } from '../../setupInspector/SetupFactsTable'
+import { type HealthPanelFinding, hoursSinceStart } from '../healthPanelFindings'
+import {
+ type HealthDebugReleaseCondition,
+ type HealthDebugSplitChange,
+ type HealthInputsState,
+ type PageMetricCounts,
+ buildExperimentFacts,
+ buildExposureFacts,
+ buildFlagFacts,
+ buildMetricFacts,
+ buildReleaseConditions,
+ buildSplitChanges,
+ buildSplitHistoryFacts,
+ buildTrafficFacts,
+} from './healthDebugInputs'
+import {
+ type HealthDebugCheck,
+ type HealthDebugDomain,
+ type HealthDebugInput,
+ buildHealthDebugChecks,
+ describePanel,
+ describeServerHealth,
+} from './healthDebugReport'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface experimentHealthDebugLogicValues {
+ browserExperimentWarning: ExperimentWarning | null // experimentLogic
+ browserNoMetricsWarning: boolean // experimentLogic
+ experiment: Experiment // experimentLogic
+ experimentHealth: ExperimentHealthApi | null // experimentLogic
+ experimentHealthLoading: boolean // experimentLogic
+ experimentLoadCount: number // experimentLogic
+ exposures: any // experimentLogic
+ exposuresLoading: boolean // experimentLogic
+ healthFindings: HealthPanelFinding[] | null // experimentLogic
+ isExperimentDraft: boolean // experimentLogic
+ currentProjectId: number | null // projectLogic
+ activeDomain: HealthDebugDomain
+ experimentFacts: SetupFact[]
+ exposureFacts: SetupFact[]
+ flagFacts: SetupFact[]
+ healthDebugChecks: HealthDebugCheck[]
+ healthDebugRawData: Record<string, unknown>
+ healthDebugSummary: SetupFact[]
+ healthInputs: ExperimentHealthInputsApi | null
+ healthInputsError: string | null
+ healthInputsLoading: boolean
+ healthInputsState: HealthInputsState
+ metricFacts: SetupFact[]
+ pageMetricCounts: PageMetricCounts
+ releaseConditions: HealthDebugReleaseCondition[]
+ splitChanges: HealthDebugSplitChange[]
+ splitHistoryFacts: SetupFact[]
+ trafficFacts: SetupFact[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface experimentHealthDebugLogicActions {
+ loadExperimentHealthSuccess: (
+ experimentHealth: ExperimentHealthApi | null,
+ payload?: ('experiment_load' | 'experiment_update') | undefined
+ ) => {
+ experimentHealth: ExperimentHealthApi | null
+ payload?: 'experiment_load' | 'experiment_update'
+ } // experimentLogic
+ loadHealthInputs: () => any
+ loadHealthInputsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadHealthInputsSuccess: (
+ healthInputs: ExperimentHealthInputsApi | null,
+ payload?: any
+ ) => {
+ healthInputs: ExperimentHealthInputsApi | null
+ payload?: any
+ }
+ setActiveDomain: (domain: HealthDebugDomain) => {
+ domain: HealthDebugDomain
+ }
+ setHealthInputsError: (error: string | null) => {
+ error: string | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface experimentHealthDebugLogicMeta {
+ key: ExperimentIdType
+ __keaTypeGenInternalSelectorTypes: {
+ pageMetricCounts: (experiment: Experiment) => PageMetricCounts
+ healthInputsState: (
+ healthInputs: ExperimentHealthInputsApi | null,
+ healthInputsLoading: boolean,
+ healthInputsError: string | null
+ ) => HealthInputsState
+ healthDebugChecks: (
+ experimentHealth: ExperimentHealthApi | null,
+ browserExperimentWarning: ExperimentWarning | null,
+ browserNoMetricsWarning: boolean,
+ isExperimentDraft: boolean,
+ exposures: any,
+ exposuresLoading: boolean,
+ healthInputs: ExperimentHealthInputsApi | null,
+ healthInputsLoading: boolean
+ ) => HealthDebugCheck[]
+ healthDebugSummary: (
+ experimentHealth: ExperimentHealthApi | null,
+ healthFindings: HealthPanelFinding[] | null,
+ healthDebugChecks: HealthDebugCheck[],
+ experimentLoadCount: number
+ ) => SetupFact[]
+ experimentFacts: (experiment: Experiment, healthInputsState: HealthInputsState) => SetupFact[]
+ flagFacts: (experiment: Experiment, healthInputsState: HealthInputsState) => SetupFact[]
+ releaseConditions: (healthInputs: ExperimentHealthInputsApi | null) => HealthDebugReleaseCondition[]
+ splitHistoryFacts: (healthInputsState: HealthInputsState) => SetupFact[]
+ splitChanges: (healthInputs: ExperimentHealthInputsApi | null) => HealthDebugSplitChange[]
+ trafficFacts: (healthInputsState: HealthInputsState) => SetupFact[]
+ metricFacts: (
+ experiment: Experiment,
+ healthInputsState: HealthInputsState,
+ pageMetricCounts: PageMetricCounts
+ ) => SetupFact[]
+ exposureFacts: (healthInputsState: HealthInputsState) => SetupFact[]
+ healthDebugRawData: (
+ experimentHealth: ExperimentHealthApi | null,
+ healthFindings: HealthPanelFinding[] | null,
+ healthInputs: ExperimentHealthInputsApi | null,
+ exposures: any
+ ) => Record<string, unknown>
+ }
+}
+
+export type experimentHealthDebugLogicType = MakeLogicType<
+ experimentHealthDebugLogicValues,
+ experimentHealthDebugLogicActions,
+ ExperimentLogicProps,
+ experimentHealthDebugLogicMeta
+>
+
+function errorDetail(error: unknown): string {
+ const { detail } = (error ?? {}) as { detail?: string }
+ return detail || 'The request failed. Reload the inputs, and check the server logs if it keeps failing.'
+}
+
+/** The staff-only view of the health checks: what each check concluded, and the inputs it read, by domain. */
+export const experimentHealthDebugLogic = kea<experimentHealthDebugLogicType>([
+ props({} as ExperimentLogicProps),
+ key((props) => props.experimentId ?? 'new'),
+ path((key) => ['products', 'experiments', 'health', 'debug', 'experimentHealthDebugLogic', key]),
+ connect((props: ExperimentLogicProps) => ({
+ values: [
+ experimentLogic(props),
+ [
+ 'experiment',
+ 'experimentHealth',
+ 'experimentHealthLoading',
+ 'healthFindings',
+ 'browserExperimentWarning',
+ 'browserNoMetricsWarning',
+ 'exposures',
+ 'exposuresLoading',
+ 'isExperimentDraft',
+ 'experimentLoadCount',
+ ],
+ projectLogic,
+ ['currentProjectId'],
+ ],
+ actions: [experimentLogic(props), ['loadExperimentHealthSuccess']],
+ })),
+ actions({
+ setActiveDomain: (domain: HealthDebugDomain) => ({ domain }),
+ setHealthInputsError: (error: string | null) => ({ error }),
+ }),
+ loaders(({ actions, props, values }) => ({
+ // The error is caught and shown in the panel, because the loader's failure path would also raise a toast for
+ // the same message.
+ healthInputs: [
+ null as ExperimentHealthInputsApi | null,
+ {
+ loadHealthInputs: async () => {
+ if (typeof props.experimentId !== 'number' || values.currentProjectId === null) {
+ return null
+ }
+ actions.setHealthInputsError(null)
+ try {
+ return await experimentsHealthInputsRetrieve(
+ String(values.currentProjectId),
+ props.experimentId
+ )
+ } catch (error) {
+ actions.setHealthInputsError(errorDetail(error))
+ return null
+ }
+ },
+ },
+ ],
+ })),
+ reducers({
+ activeDomain: ['experiment' as HealthDebugDomain, { setActiveDomain: (_, { domain }) => domain }],
+ healthInputsError: [null as string | null, { setHealthInputsError: (_, { error }) => error }],
+ }),
+ selectors({
+ pageMetricCounts: [
+ (s) => [s.experiment],
+ (experiment: Experiment): PageMetricCounts => ({
+ primary: getSectionMetricUuids(experiment, false).length,
+ secondary: getSectionMetricUuids(experiment, true).length,
+ }),
+ ],
+ healthInputsState: [
+ (s) => [s.healthInputs, s.healthInputsLoading, s.healthInputsError],
+ (inputs: ExperimentHealthInputsApi | null, loading: boolean, error: string | null): HealthInputsState => ({
+ inputs,
+ loading,
+ error,
+ }),
+ ],
+ healthDebugChecks: [
+ (s) => [
+ s.experimentHealth,
+ s.browserExperimentWarning,
+ s.browserNoMetricsWarning,
+ s.isExperimentDraft,
+ s.exposures,
+ s.exposuresLoading,
+ s.healthInputs,
+ s.healthInputsLoading,
+ ],
+ (
+ experimentHealth: ExperimentHealthApi | null,
+ browserWarning: ExperimentWarning | null,
+ browserNoMetricsWarning: boolean,
+ isExperimentDraft: boolean,
+ exposures: HealthDebugInput['exposures'],
+ exposuresLoading: boolean,
+ healthInputs: ExperimentHealthInputsApi | null,
+ healthInputsLoading: boolean
+ ): HealthDebugCheck[] =>
+ buildHealthDebugChecks({
+ health: experimentHealth,
+ browserWarning,
+ browserNoMetricsWarning,
+ isExperimentDraft,
+ exposures,
+ exposuresLoading,
+ serverExposures: healthInputs?.exposures ?? null,
+ serverExposuresLoading: healthInputsLoading,
+ }),
+ ],
+ healthDebugSummary: [
+ (s) => [s.experimentHealth, s.healthFindings, s.healthDebugChecks, s.experimentLoadCount],
+ (
+ experimentHealth: ExperimentHealthApi | null,
+ healthFindings: HealthPanelFinding[] | null,
+ checks: HealthDebugCheck[],
+ experimentLoadCount: number
+ ): SetupFact[] => {
+ const differing = checks
+ .filter(({ difference }) => difference === 'disagrees')
+ .map(({ check }) => check)
+ return [
+ { label: 'Server health', value: describeServerHealth(experimentHealth) },
+ { label: 'Health panel', value: describePanel(healthFindings) },
+ {
+ label: 'Browser rules',
+ value: differing.length ? `Differ from the server on ${differing.join(', ')}` : 'Agree',
+ help: "The page's older rules for the flag state and the metrics. The page shows the server's findings when it has them.",
+ },
+ {
+ label: 'Page load',
+ value: String(experimentLoadCount),
+ help: 'Each finding is reported as shown once per load.',
+ },
+ ]
+ },
+ ],
+ experimentFacts: [
+ (s) => [s.experiment, s.healthInputsState],
+ (experiment: Experiment, state: HealthInputsState): SetupFact[] =>
+ buildExperimentFacts(experiment, state, hoursSinceStart(experiment.start_date)),
+ ],
+ flagFacts: [
+ (s) => [s.experiment, s.healthInputsState],
+ (experiment: Experiment, state: HealthInputsState): SetupFact[] => buildFlagFacts(experiment, state),
+ ],
+ releaseConditions: [
+ (s) => [s.healthInputs],
+ (inputs: ExperimentHealthInputsApi | null): HealthDebugReleaseCondition[] => buildReleaseConditions(inputs),
+ ],
+ splitHistoryFacts: [
+ (s) => [s.healthInputsState],
+ (state: HealthInputsState): SetupFact[] => buildSplitHistoryFacts(state),
+ ],
+ splitChanges: [
+ (s) => [s.healthInputs],
+ (inputs: ExperimentHealthInputsApi | null): HealthDebugSplitChange[] => buildSplitChanges(inputs),
+ ],
+ trafficFacts: [
+ (s) => [s.healthInputsState],
+ (state: HealthInputsState): SetupFact[] => buildTrafficFacts(state),
+ ],
+ metricFacts: [
+ (s) => [s.experiment, s.healthInputsState, s.pageMetricCounts],
+ (experiment: Experiment, state: HealthInputsState, pageMetricCounts: PageMetricCounts): SetupFact[] =>
+ buildMetricFacts(experiment, state, pageMetricCounts),
+ ],
+ exposureFacts: [
+ (s) => [s.healthInputsState],
+ (state: HealthInputsState): SetupFact[] => buildExposureFacts(state),
+ ],
+ healthDebugRawData: [
+ (s) => [s.experimentHealth, s.healthFindings, s.healthInputs, s.exposures],
+ (
+ experimentHealth: ExperimentHealthApi | null,
+ healthFindings: HealthPanelFinding[] | null,
+ healthInputs: ExperimentHealthInputsApi | null,
+ exposures: any
+ ): Record<string, unknown> => ({
+ health: experimentHealth,
+ panelFindings: healthFindings,
+ healthInputs,
+ pageExposures: exposures
+ ? {
+ total_exposures: exposures.total_exposures,
+ sample_ratio_mismatch: exposures.sample_ratio_mismatch,
+ bias_risk: exposures.bias_risk,
+ }
+ : null,
+ }),
+ ],
+ }),
+ listeners(({ actions }) => ({
+ // The inputs follow the findings, so that both describe the same save of the experiment.
+ loadExperimentHealthSuccess: () => {
+ actions.loadHealthInputs()
+ },
+ })),
+ afterMount(({ actions, values }) => {
+ // While the findings load, their success loads the inputs, so loading here too would ask twice.
+ if (!values.experimentHealthLoading) {
+ actions.loadHealthInputs()
+ }
+ }),
+])
diff --git a/products/experiments/frontend/health/debug/healthDebugInputs.ts b/products/experiments/frontend/health/debug/healthDebugInputs.ts
new file mode 100644
index 000000000000..6578224f928a
--- /dev/null
+++ b/products/experiments/frontend/health/debug/healthDebugInputs.ts
@@ -0,0 +1,360 @@
+import type { Experiment } from '~/types'
+
+import { EXPERIMENT_VARIANT_MULTIPLE } from '../../constants'
+import { getExperimentStatus } from '../../experimentStatus'
+import type {
+ ExperimentHealthInputsApi,
+ ExperimentHealthInputsExposuresApi,
+ ExperimentHealthInputsSplitHistoryApi,
+ ExperimentHealthInputsTrafficStatusEnumApi,
+ ExperimentHealthInputsVariantApi,
+ HealthExposureInputsStatusEnumApi,
+} from '../../generated/api.schemas'
+import type { SetupFact } from '../../setupInspector/SetupFactsTable'
+import { formatCount, formatShare, formatTimestamp, formatYesNo } from '../../setupInspector/setupInspectorUtils'
+
+export interface HealthInputsState {
+ inputs: ExperimentHealthInputsApi | null
+ loading: boolean
+ error: string | null
+}
+
+export interface HealthDebugReleaseCondition {
+ number: number
+ rolloutPercentage: number | null
+ propertyCount: number | null
+ reachable: boolean
+ pinnedVariant: string | null
+ /** People this condition served in the traffic window. Null when the traffic was not read. */
+ people: number | null
+}
+
+export interface HealthDebugSplitChange {
+ changedAt: string
+ before: string
+ after: string
+ counted: boolean
+}
+
+export interface PageMetricCounts {
+ primary: number
+ secondary: number
+}
+
+function serverValue(state: HealthInputsState, read: (inputs: ExperimentHealthInputsApi) => string): string {
+ if (state.inputs) {
+ return read(state.inputs)
+ }
+ if (state.loading) {
+ return 'Loading…'
+ }
+ return state.error ? `Not loaded: ${state.error}` : 'Not loaded'
+}
+
+function percentage(value: number | null): string {
+ return value === null ? 'unset' : `${value}%`
+}
+
+export function describeSplit(variants: ExperimentHealthInputsVariantApi[]): string {
+ return variants.length
+ ? variants.map((variant) => `${variant.key ?? 'no key'} ${percentage(variant.rollout_percentage)}`).join(', ')
+ : 'none'
+}
+
+function yesNoUnknown(value: boolean | null): string {
+ return value === null ? 'Unknown' : formatYesNo(value)
+}
+
+function describeState(inputs: ExperimentHealthInputsApi): string {
+ if (!inputs.is_launched) {
+ return 'not launched'
+ }
+ const states = [
+ inputs.is_running && 'running',
+ inputs.is_paused && 'paused',
+ inputs.has_ended && 'ended',
+ inputs.archived && 'archived',
+ ].filter(Boolean)
+ return ['launched', ...states].join(', ')
+}
+
+export function buildExperimentFacts(
+ experiment: Experiment,
+ state: HealthInputsState,
+ hoursSinceStart: number | null
+): SetupFact[] {
+ return [
+ { label: 'Status on the page', value: getExperimentStatus(experiment) },
+ {
+ label: 'State the checks read',
+ value: serverValue(state, describeState),
+ help: 'The flag-state, split-change and forced-variant checks only fire for some of these states.',
+ },
+ { label: 'Start date', value: formatTimestamp(experiment.start_date) },
+ {
+ label: 'Hours since start',
+ value: hoursSinceStart === null ? 'Not launched' : String(Math.floor(hoursSinceStart)),
+ help: 'The zero-exposures finding waits for a few hours after launch.',
+ },
+ { label: 'End date', value: formatTimestamp(experiment.end_date) },
+ {
+ label: 'Baseline variant',
+ value: serverValue(state, (inputs) => inputs.baseline_variant_key ?? 'Not set, the analysis picks one'),
+ help: 'The flag-variants check needs the baseline to be one of the flag variants.',
+ },
+ {
+ label: 'Excluded from the analysis',
+ value: serverValue(state, (inputs) => inputs.excluded_variant_keys.join(', ') || 'None'),
+ help: 'The forced-variant check ignores pins to these variants.',
+ },
+ {
+ label: 'Your access',
+ value: serverValue(
+ state,
+ ({ reader_access }) =>
+ `Flag history: ${formatYesNo(reader_access.can_read_flag_history).toLowerCase()}. Event queries: ${formatYesNo(reader_access.can_query_events).toLowerCase()}. Denied event properties: ${reader_access.denied_event_properties.join(', ') || 'none'}.`
+ ),
+ help: 'The split-change and forced-variant checks read only what the person loading the page may read. A customer without this access gets other findings than you.',
+ },
+ ]
+}
+
+export function buildFlagFacts(experiment: Experiment, state: HealthInputsState): SetupFact[] {
+ return [
+ { label: 'Key', value: experiment.feature_flag?.key ?? 'None' },
+ {
+ label: 'Enabled',
+ value: serverValue(state, ({ flag }) => (flag ? formatYesNo(flag.active) : 'No flag')),
+ },
+ {
+ label: 'Deleted',
+ value: serverValue(state, ({ flag }) => (flag ? formatYesNo(flag.deleted) : 'No flag')),
+ },
+ {
+ label: 'Variants',
+ value: serverValue(state, ({ flag }) => (flag ? describeSplit(flag.variants) : 'No flag')),
+ },
+ ]
+}
+
+export function buildReleaseConditions(inputs: ExperimentHealthInputsApi | null): HealthDebugReleaseCondition[] {
+ const traffic = inputs?.condition_set_traffic
+ const peopleBySet = new Map(traffic?.people_by_set.map(({ condition_set, people }) => [condition_set, people]))
+ return (inputs?.flag?.release_conditions ?? []).map((condition) => ({
+ number: condition.number,
+ rolloutPercentage: condition.rollout_percentage,
+ propertyCount: condition.property_count,
+ reachable: condition.reachable,
+ pinnedVariant: condition.pinned_variant,
+ people: traffic ? (peopleBySet.get(condition.number) ?? 0) : null,
+ }))
+}
+
+function describeSplitHistoryStatus(inputs: ExperimentHealthInputsApi): string {
+ const history = inputs.split_history
+ if (history) {
+ if (!history.checked) {
+ return `Not compared: ${history.not_checked_reason}`
+ }
+ const total = history.changes.length
+ const counted = history.changes.filter((change) => change.counted).length
+ if (total === 0) {
+ return 'No split changes since launch'
+ }
+ if (total === 1) {
+ return counted
+ ? 'Compared with the exposures: the change counts'
+ : 'Compared with the exposures: nobody was exposed before the change, so it does not count'
+ }
+ return counted === 0
+ ? `Compared with the exposures: nobody was exposed before any of the ${total} changes, so none counts`
+ : `Compared with the exposures: ${counted} of ${total} changes count`
+ }
+ if (!inputs.is_running) {
+ return 'Not read: the experiment is not running'
+ }
+ if (inputs.archived) {
+ return 'Not read: the experiment is archived'
+ }
+ if (!inputs.flag || inputs.flag.deleted) {
+ return 'Not read: the flag is missing or deleted'
+ }
+ return 'Not read: the read failed'
+}
+
+export function buildSplitHistoryFacts(state: HealthInputsState): SetupFact[] {
+ const history: ExperimentHealthInputsSplitHistoryApi | null = state.inputs?.split_history ?? null
+ const hasCountedChange = !!history?.changes.some((change) => change.counted)
+ return [
+ {
+ label: 'Status',
+ value: serverValue(state, describeSplitHistoryStatus),
+ help: 'The split-change check compares the changes with the exposures only for an exposure event without property filters.',
+ },
+ ...(history
+ ? [{ label: 'Launched at', value: `${formatTimestamp(history.launched_at)} (${history.team_timezone})` }]
+ : []),
+ ...(hasCountedChange && history
+ ? [
+ {
+ label: 'Exposed before the first counted change',
+ value: yesNoUnknown(history.exposed_before_first),
+ },
+ {
+ label: 'Exposed between the first and last change',
+ value: yesNoUnknown(history.exposed_between),
+ help: 'Asked only when the last change sets the split back to what it was before the first.',
+ },
+ ]
+ : []),
+ ]
+}
+
+export function buildSplitChanges(inputs: ExperimentHealthInputsApi | null): HealthDebugSplitChange[] {
+ return (inputs?.split_history?.changes ?? []).map((change) => ({
+ changedAt: formatTimestamp(change.changed_at),
+ before: describeSplit(change.before),
+ after: describeSplit(change.after),
+ counted: change.counted,
+ }))
+}
+
+const TRAFFIC_STATUS_LABELS: Record<ExperimentHealthInputsTrafficStatusEnumApi, string> = {
+ read: 'Read',
+ not_needed: 'Not read: the forced-variant check does not need it',
+ no_query_access: 'Not read: you may not query events',
+ denied_properties: 'Not read: you are denied a flag call property that the scan reads',
+ no_flag_version: "Not read: the flag has no version, so its calls can't be matched to it",
+ unknown: "Not read: the scan failed or was too expensive, or another request's scan did not answer in time",
+}
+
+export function buildTrafficFacts(state: HealthInputsState): SetupFact[] {
+ const traffic = state.inputs?.condition_set_traffic ?? null
+ const people = traffic?.people_by_set.reduce((sum, { people }) => sum + people, 0) ?? 0
+ return [
+ {
+ label: 'Status',
+ value: serverValue(state, (inputs) => TRAFFIC_STATUS_LABELS[inputs.condition_set_traffic_status]),
+ help: 'The forced-variant check reads the calls when the experiment is launched and some, but not all, release conditions pin a variant that has a share of the split and is not excluded from the analysis.',
+ },
+ ...(traffic
+ ? [
+ { label: 'Since', value: `${formatTimestamp(traffic.since)} (${traffic.team_timezone})` },
+ { label: 'Calls', value: formatCount(traffic.calls) },
+ {
+ label: 'Evaluated by the flag service',
+ value: `${formatCount(traffic.remotely_evaluated_calls)} (${formatShare(traffic.calls ? traffic.remotely_evaluated_calls / traffic.calls : null)})`,
+ help: 'Only these calls name the condition that served them. Local evaluation and bootstrapped values name none.',
+ },
+ { label: 'People served by a named condition', value: formatCount(people) },
+ ]
+ : []),
+ ]
+}
+
+export function buildMetricFacts(
+ experiment: Experiment,
+ state: HealthInputsState,
+ pageMetricCounts: PageMetricCounts
+): SetupFact[] {
+ const sharedMetricTypes = (experiment.saved_metrics ?? []).map(
+ (link: { metadata?: { type?: string } }) => link.metadata?.type ?? 'none'
+ )
+ const countType = (type: string): number => sharedMetricTypes.filter((linkType) => linkType === type).length
+ return [
+ {
+ label: 'Metrics the checks count',
+ value: serverValue(
+ state,
+ (inputs) => `${inputs.primary_metric_count} primary, ${inputs.secondary_metric_count} secondary`
+ ),
+ help: 'The no-metric check fires when both are zero.',
+ },
+ {
+ label: 'Metrics the page lists',
+ value: `${pageMetricCounts.primary} primary, ${pageMetricCounts.secondary} secondary`,
+ help: "The browser's no-metric rule reads these.",
+ },
+ {
+ label: 'Single-use metrics',
+ value: `${experiment.metrics?.length ?? 0} primary, ${experiment.metrics_secondary?.length ?? 0} secondary`,
+ },
+ {
+ label: 'Shared metric links',
+ value: `${countType('primary')} primary, ${countType('secondary')} secondary, ${countType('none')} without a type`,
+ },
+ ]
+}
+
+const EXPOSURE_STATUS_LABELS: Record<HealthExposureInputsStatusEnumApi, string> = {
+ ready: 'Read from the cache',
+ stale: 'Read from the cache, which is past its age. A recalculation runs in the background.',
+ calculating: 'No cached answer. A calculation runs in the background, so reload the inputs in a minute.',
+ not_launched: 'None, the experiment is not launched',
+ no_query_access: 'Not read: you may not query events',
+ failed: 'The exposure query failed',
+}
+
+function exposureStatusLabel(exposures: ExperimentHealthInputsExposuresApi): string {
+ if (!exposures.error) {
+ return EXPOSURE_STATUS_LABELS[exposures.status]
+ }
+ // A stale answer with an error means the recalculation failed, and no new one runs yet.
+ const label =
+ exposures.status === 'stale'
+ ? 'Read from the cache, which is past its age. The last recalculation failed'
+ : EXPOSURE_STATUS_LABELS[exposures.status]
+ return `${label}: ${exposures.error}`
+}
+
+export function buildExposureFacts(state: HealthInputsState): SetupFact[] {
+ const exposures = state.inputs?.exposures
+ const facts: SetupFact[] = [
+ {
+ label: 'Status',
+ value: serverValue(state, (inputs) => exposureStatusLabel(inputs.exposures)),
+ help: 'The server reads the cached answer and never waits for the query.',
+ },
+ ]
+ const totals = exposures?.totals
+ if (!exposures || !totals) {
+ return facts
+ }
+ const total = Object.values(totals.total_exposures).reduce((sum, count) => sum + count, 0)
+ const byVariant = Object.entries(totals.total_exposures)
+ .map(([variant, count]) => `${variant} ${formatCount(count)}`)
+ .join(', ')
+ const pValue = totals.sample_ratio_mismatch_p_value
+ return [
+ ...facts,
+ { label: 'Computed at', value: formatTimestamp(exposures.computed_at) },
+ {
+ label: 'Hours since launch at computation',
+ value: totals.hours_since_launch === null ? 'Not launched' : String(Math.floor(totals.hours_since_launch)),
+ help: 'The zero-exposures check waits for a few hours after launch.',
+ },
+ {
+ label: 'Exposed users',
+ value: formatCount(total),
+ help: `Includes the users in several variants, as the zero-exposures and bias checks count them.`,
+ },
+ { label: 'By variant', value: byVariant || 'None' },
+ {
+ label: 'Users in several variants',
+ value: formatCount(totals.total_exposures[EXPERIMENT_VARIANT_MULTIPLE] ?? 0),
+ help: `Reported as ${EXPERIMENT_VARIANT_MULTIPLE}.`,
+ },
+ { label: 'Multiple variant handling', value: totals.multiple_variant_handling },
+ {
+ label: 'Sample ratio test',
+ value: pValue !== null ? `p = ${pValue.toPrecision(3)}` : 'Not run, too little data',
+ help: 'The SRM finding needs p < 0.001.',
+ },
+ {
+ label: 'Findings on this answer',
+ value: exposures.findings.length
+ ? exposures.findings.map((finding) => `${finding.code} (${finding.severity})`).join(', ')
+ : 'None',
+ },
+ ]
+}
diff --git a/products/experiments/frontend/health/healthDebugReport.test.ts b/products/experiments/frontend/health/debug/healthDebugReport.test.ts
similarity index 53%
rename from products/experiments/frontend/health/healthDebugReport.test.ts
rename to products/experiments/frontend/health/debug/healthDebugReport.test.ts
index 7830fa090c57..98850a445b54 100644
--- a/products/experiments/frontend/health/healthDebugReport.test.ts
+++ b/products/experiments/frontend/health/debug/healthDebugReport.test.ts
@@ -1,6 +1,6 @@
import type { ExperimentWarning } from 'scenes/experiments/experimentLogic'
-import type { ExperimentHealthApi, ExperimentHealthFindingApi } from '../generated/api.schemas'
+import type { ExperimentHealthApi, ExperimentHealthFindingApi } from '../../generated/api.schemas'
import { type HealthDebugInput, buildHealthDebugChecks } from './healthDebugReport'
const PAUSED: ExperimentHealthFindingApi = {
@@ -16,15 +16,13 @@ const PAUSED: ExperimentHealthFindingApi = {
const input = (overrides: Partial<HealthDebugInput>): HealthDebugInput => ({
health: { findings: [] },
- panelFindings: [],
browserWarning: null,
browserNoMetricsWarning: false,
- pageMetricCounts: { primary: 1, secondary: 0 },
isExperimentDraft: false,
- hoursSinceStart: 72,
exposures: null,
exposuresLoading: false,
- multipleVariantHandling: 'exclude',
+ serverExposures: null,
+ serverExposuresLoading: false,
...overrides,
})
@@ -34,6 +32,7 @@ describe('buildHealthDebugChecks', () => {
health: ExperimentHealthApi | null
browserWarning: ExperimentWarning | null
browserNoMetricsWarning: boolean
+ extra?: Partial<HealthDebugInput>
expected: string[]
}>([
{
@@ -48,21 +47,60 @@ describe('buildHealthDebugChecks', () => {
health: { findings: [PAUSED] },
browserWarning: null,
browserNoMetricsWarning: false,
- expected: ['flag_state'],
+ expected: ['flag_state:disagrees'],
},
{
name: 'a flag-state subcode the page does not know, while the browser finds nothing',
health: { findings: [{ ...PAUSED, subcode: 'running_but_unknown_case' }] },
browserWarning: null,
browserNoMetricsWarning: false,
- expected: ['flag_state'],
+ expected: ['flag_state:disagrees'],
},
{
name: 'no metrics on the page while the server counts one',
health: { findings: [] },
browserWarning: null,
browserNoMetricsWarning: true,
- expected: ['no_metric'],
+ expected: ['no_metric:disagrees'],
+ },
+ {
+ name: "an SRM finding in the server's exposure answer only",
+ health: { findings: [] },
+ browserWarning: null,
+ browserNoMetricsWarning: false,
+ extra: {
+ exposures: { total_exposures: {}, timeseries: [], date_range: { date_from: null } } as any,
+ serverExposures: {
+ status: 'ready',
+ computed_at: null,
+ totals: null,
+ findings: [{ ...PAUSED, code: 'srm', subcode: null, severity: 'warning' }],
+ error: null,
+ },
+ },
+ expected: ['srm:drift'],
+ },
+ {
+ name: 'the same SRM finding in both answers while the health request failed',
+ health: null,
+ browserWarning: null,
+ browserNoMetricsWarning: false,
+ extra: {
+ exposures: {
+ total_exposures: {},
+ timeseries: [],
+ date_range: { date_from: null },
+ health_findings: [{ ...PAUSED, code: 'srm', subcode: null, severity: 'warning' }],
+ } as any,
+ serverExposures: {
+ status: 'ready',
+ computed_at: null,
+ totals: null,
+ findings: [{ ...PAUSED, code: 'srm', subcode: null, severity: 'warning' }],
+ error: null,
+ },
+ },
+ expected: [],
},
{
name: 'nothing to compare without server health',
@@ -71,9 +109,11 @@ describe('buildHealthDebugChecks', () => {
browserNoMetricsWarning: true,
expected: [],
},
- ])('$name', ({ health, browserWarning, browserNoMetricsWarning, expected }) => {
- const checks = buildHealthDebugChecks(input({ health, browserWarning, browserNoMetricsWarning }))
+ ])('$name', ({ health, browserWarning, browserNoMetricsWarning, extra, expected }) => {
+ const checks = buildHealthDebugChecks(input({ health, browserWarning, browserNoMetricsWarning, ...extra }))
- expect(checks.filter(({ differs }) => differs).map(({ check }) => check)).toEqual(expected)
+ expect(
+ checks.filter(({ difference }) => difference).map(({ check, difference }) => `${check}:${difference}`)
+ ).toEqual(expected)
})
})
diff --git a/products/experiments/frontend/health/debug/healthDebugReport.ts b/products/experiments/frontend/health/debug/healthDebugReport.ts
new file mode 100644
index 000000000000..b1574c5037c5
--- /dev/null
+++ b/products/experiments/frontend/health/debug/healthDebugReport.ts
@@ -0,0 +1,316 @@
+import type { ExperimentWarning } from 'scenes/experiments/experimentLogic'
+
+import type { ExperimentExposureQueryResponse } from '~/queries/schema/schema-general'
+
+import type {
+ ExperimentHealthApi,
+ ExperimentHealthFindingApi,
+ ExperimentHealthInputsExposuresApi,
+ HealthExposureInputsStatusEnumApi,
+} from '../../generated/api.schemas'
+import { FLAG_STATE_FINDING_CODES, experimentWarningFromHealth } from '../experimentHealthFindingEvents'
+import type { HealthPanelFinding } from '../healthPanelFindings'
+
+export type HealthDebugDomain = 'experiment' | 'flag' | 'exposures' | 'metrics' | 'project' | 'raw'
+
+export const HEALTH_DEBUG_DOMAIN_LABELS: Record<HealthDebugDomain, string> = {
+ experiment: 'Experiment',
+ flag: 'Feature flag',
+ exposures: 'Exposures',
+ metrics: 'Metrics',
+ project: 'Project',
+ raw: 'Raw data',
+}
+
+export type HealthDebugSource = 'health endpoint' | 'exposure query'
+
+export interface HealthDebugCheck {
+ check: string
+ source: HealthDebugSource
+ /** The input domains the check reads, as the input tabs name them. */
+ reads: HealthDebugDomain[]
+ result: string
+ /** The severity of the finding behind the result. Null when the check gave no finding. */
+ severity: HealthPanelFinding['severity'] | null
+ /** What the page gives for the same check: its older rules, or its own exposure answer. Null when it has none. */
+ browser: string | null
+ browserLabel: string
+ /** When the server's answer and the page's were computed, for the exposure checks. Null otherwise. */
+ computedAt: string | null
+ browserComputedAt: string | null
+ /** 'disagrees' when the page's rules and the server's check read the same state and differ. 'drift' when the
+ * server's exposure answer and the page's differ, which is expected, because they are computed at other times. */
+ difference: 'disagrees' | 'drift' | null
+ /** The values behind the result, or why the check gave none. */
+ note: string | null
+}
+
+export interface HealthDebugInput {
+ health: ExperimentHealthApi | null
+ browserWarning: ExperimentWarning | null
+ browserNoMetricsWarning: boolean
+ isExperimentDraft: boolean
+ exposures: ExperimentExposureQueryResponse | null | undefined
+ exposuresLoading: boolean
+ /** The exposure answer that the server's exposure checks read. Null until the health inputs load. */
+ serverExposures: ExperimentHealthInputsExposuresApi | null
+ serverExposuresLoading: boolean
+}
+
+const NO_FINDING = 'no finding'
+const NOT_LOADED = 'not loaded'
+const BROWSER_RULES = 'Browser rules'
+const NO_TIMES = { computedAt: null, browserComputedAt: null }
+
+const SERVER_EXPOSURES_UNAVAILABLE: Record<Exclude<HealthExposureInputsStatusEnumApi, 'ready' | 'stale'>, string> = {
+ calculating: 'calculating: no cached answer yet',
+ not_launched: 'skipped: not launched',
+ no_query_access: 'skipped: you may not query events',
+ failed: 'failed: the exposure query failed',
+}
+
+export function describeServerHealth(health: ExperimentHealthApi | null): string {
+ return health ? `${health.findings.length} findings` : `${NOT_LOADED}: the health request is pending or failed`
+}
+
+export function describePanel(panelFindings: HealthPanelFinding[] | null): string {
+ if (panelFindings === null) {
+ return 'hidden: no server health, so the page shows its separate warnings'
+ }
+ if (panelFindings.length === 0) {
+ return 'hidden: no findings'
+ }
+ return `shows ${panelFindings.length} findings`
+}
+
+function warningLabel(warning: ExperimentWarning | null): string {
+ if (!warning) {
+ return NO_FINDING
+ }
+ return warning.variantKey ? `${warning.key} (${warning.variantKey})` : warning.key
+}
+
+interface CheckResult {
+ result: string
+ severity: HealthPanelFinding['severity'] | null
+}
+
+function describeFinding(check: string, finding: Pick<HealthPanelFinding, 'code' | 'subcode' | 'evidence'>): string {
+ const variantKey = finding.evidence.variant_key
+ const name = finding.code === check ? finding.subcode : [finding.code, finding.subcode].filter(Boolean).join(' · ')
+ return [name || 'finding', typeof variantKey === 'string' ? `(${variantKey})` : null].filter(Boolean).join(' ')
+}
+
+function serverResult(
+ check: string,
+ health: ExperimentHealthApi | null,
+ matches: (code: ExperimentHealthFindingApi['code']) => boolean
+): CheckResult {
+ if (!health) {
+ return { result: NOT_LOADED, severity: null }
+ }
+ const finding = health.findings.find((candidate) => matches(candidate.code))
+ return finding
+ ? { result: describeFinding(check, finding), severity: finding.severity }
+ : { result: NO_FINDING, severity: null }
+}
+
+function findingOf(
+ input: HealthDebugInput,
+ code: ExperimentHealthFindingApi['code']
+): ExperimentHealthFindingApi | null {
+ return input.health?.findings.find((finding) => finding.code === code) ?? null
+}
+
+function flagStateCheck(input: HealthDebugInput): HealthDebugCheck {
+ const serverWarning = input.health ? experimentWarningFromHealth(input.health) : null
+ // A subcode the page does not know maps to no warning, so it can match a browser that finds none.
+ // The raw finding still counts as a difference then.
+ const hasUnmappedServerFinding =
+ !serverWarning && !!input.health?.findings.some((finding) => FLAG_STATE_FINDING_CODES.has(finding.code))
+ const differs =
+ !!input.health &&
+ (hasUnmappedServerFinding || warningLabel(serverWarning) !== warningLabel(input.browserWarning))
+ return {
+ check: 'flag_state',
+ source: 'health endpoint',
+ reads: ['experiment', 'flag'],
+ ...serverResult('flag_state', input.health, (code) => FLAG_STATE_FINDING_CODES.has(code)),
+ browser: warningLabel(input.browserWarning),
+ browserLabel: BROWSER_RULES,
+ ...NO_TIMES,
+ difference: differs ? 'disagrees' : null,
+ note: differs ? "The page shows the server's finding." : null,
+ }
+}
+
+function splitChangedNote(finding: ExperimentHealthFindingApi): string {
+ const { evidence } = finding
+ if (finding.subcode === 'not_checked') {
+ return evidence.change_count == null
+ ? `Not checked: ${evidence.reason}.`
+ : `Not checked: ${evidence.reason}. ${evidence.change_count} changes since launch, from ${evidence.from} to ${evidence.to}.`
+ }
+ const exposedBefore = evidence.exposed_before_change
+ return `${evidence.change_count} counted changes, from ${evidence.from} to ${evidence.to}. Exposed before the first: ${exposedBefore == null ? 'unknown' : exposedBefore ? 'yes' : 'no'}.`
+}
+
+function splitChangedCheck(input: HealthDebugInput): HealthDebugCheck {
+ const finding = findingOf(input, 'split_changed_mid_run')
+ return {
+ check: 'split_changed_mid_run',
+ source: 'health endpoint',
+ reads: ['experiment', 'flag'],
+ ...serverResult('split_changed_mid_run', input.health, (code) => code === 'split_changed_mid_run'),
+ browser: null,
+ browserLabel: BROWSER_RULES,
+ ...NO_TIMES,
+ difference: null,
+ note: finding ? splitChangedNote(finding) : null,
+ }
+}
+
+function flagVariantsCheck(input: HealthDebugInput): HealthDebugCheck {
+ return {
+ check: 'flag_variants_mismatch',
+ source: 'health endpoint',
+ reads: ['experiment', 'flag'],
+ ...serverResult('flag_variants_mismatch', input.health, (code) => code === 'flag_variants_mismatch'),
+ browser: null,
+ browserLabel: BROWSER_RULES,
+ ...NO_TIMES,
+ difference: null,
+ note: null,
+ }
+}
+
+function share(value: unknown): string | null {
+ return typeof value === 'number' ? `${(value * 100).toFixed(1)}%` : null
+}
+
+function forcedVariantNote(finding: ExperimentHealthFindingApi): string {
+ const { evidence } = finding
+ const parts = [`Pinned sets: ${evidence.pinned_condition_sets}, to ${evidence.pinned_variant_keys}.`]
+ if (typeof evidence.pinned_people === 'number') {
+ parts.push(`${evidence.pinned_people} of ${evidence.matched_people} matched people pinned.`)
+ }
+ const pinnedShare = share(evidence.pinned_share)
+ if (pinnedShare) {
+ parts.push(`Pinned share ${pinnedShare}.`)
+ }
+ const remoteShare = share(evidence.remotely_evaluated_share)
+ if (remoteShare) {
+ parts.push(`${remoteShare} of calls evaluated by the flag service.`)
+ }
+ if (typeof evidence.reason === 'string') {
+ parts.push(`Share unknown: ${evidence.reason}.`)
+ }
+ return parts.join(' ')
+}
+
+function forcedVariantCheck(input: HealthDebugInput): HealthDebugCheck {
+ const finding = findingOf(input, 'forced_variant_release_condition')
+ return {
+ check: 'forced_variant_release_condition',
+ source: 'health endpoint',
+ reads: ['experiment', 'flag'],
+ ...serverResult(
+ 'forced_variant_release_condition',
+ input.health,
+ (code) => code === 'forced_variant_release_condition'
+ ),
+ browser: null,
+ browserLabel: BROWSER_RULES,
+ ...NO_TIMES,
+ difference: null,
+ note: finding ? forcedVariantNote(finding) : null,
+ }
+}
+
+function noMetricCheck(input: HealthDebugInput): HealthDebugCheck {
+ const serverFires = !!findingOf(input, 'no_metric')
+ const differs = !!input.health && input.browserNoMetricsWarning !== serverFires
+ return {
+ check: 'no_metric',
+ source: 'health endpoint',
+ reads: ['metrics'],
+ ...serverResult('no_metric', input.health, (code) => code === 'no_metric'),
+ browser: input.browserNoMetricsWarning ? 'no_metric' : NO_FINDING,
+ browserLabel: BROWSER_RULES,
+ ...NO_TIMES,
+ difference: differs ? 'disagrees' : null,
+ note: differs ? "The page shows the server's finding." : null,
+ }
+}
+
+function serverExposureResult(input: HealthDebugInput, code: HealthPanelFinding['code']): CheckResult {
+ const exposures = input.serverExposures
+ if (!exposures) {
+ return { result: input.serverExposuresLoading ? 'loading' : NOT_LOADED, severity: null }
+ }
+ if (exposures.status !== 'ready' && exposures.status !== 'stale') {
+ return { result: SERVER_EXPOSURES_UNAVAILABLE[exposures.status], severity: null }
+ }
+ const finding = exposures.findings.find((candidate) => candidate.code === code)
+ return finding
+ ? { result: describeFinding(code, finding), severity: finding.severity }
+ : { result: NO_FINDING, severity: null }
+}
+
+function pageExposureResult(input: HealthDebugInput, code: HealthPanelFinding['code']): string | null {
+ if (input.isExperimentDraft || !input.exposures) {
+ return null
+ }
+ // Read from the page's own answer, which holds its findings even when the health panel is unavailable.
+ const finding = input.exposures.health_findings?.find((candidate) => candidate.code === code)
+ return finding ? describeFinding(code, finding) : NO_FINDING
+}
+
+// The page's answer comes from the cache, but its type does not declare the cache fields.
+function pageComputedAt(exposures: HealthDebugInput['exposures']): string | null {
+ return exposures && 'last_refresh' in exposures && typeof exposures.last_refresh === 'string'
+ ? exposures.last_refresh
+ : null
+}
+
+function exposureChecks(input: HealthDebugInput): HealthDebugCheck[] {
+ const exposureCheck = (
+ check: HealthPanelFinding['code'],
+ reads: HealthDebugDomain[],
+ note: string | null
+ ): HealthDebugCheck => {
+ const server = serverExposureResult(input, check)
+ const page = pageExposureResult(input, check)
+ const serverAnswered = input.serverExposures?.status === 'ready' || input.serverExposures?.status === 'stale'
+ return {
+ check,
+ source: 'exposure query',
+ reads,
+ ...server,
+ browser: page,
+ browserLabel: "Page's exposure answer",
+ computedAt: serverAnswered ? (input.serverExposures?.computed_at ?? null) : null,
+ browserComputedAt: page !== null ? pageComputedAt(input.exposures) : null,
+ difference: serverAnswered && page !== null && page !== server.result ? 'drift' : null,
+ note,
+ }
+ }
+
+ return [
+ exposureCheck('zero_exposures', ['experiment', 'exposures'], null),
+ exposureCheck('srm', ['exposures'], 'The finding needs p < 0.001.'),
+ exposureCheck('bias_risk_multiple_excluded', ['exposures'], null),
+ ]
+}
+
+/** One row per check, so a reader can see why the health panel shows what it shows. */
+export function buildHealthDebugChecks(input: HealthDebugInput): HealthDebugCheck[] {
+ return [
+ flagStateCheck(input),
+ splitChangedCheck(input),
+ flagVariantsCheck(input),
+ forcedVariantCheck(input),
+ noMetricCheck(input),
+ ...exposureChecks(input),
+ ]
+}
diff --git a/products/experiments/frontend/health/experimentHealthDebugLogic.ts b/products/experiments/frontend/health/experimentHealthDebugLogic.ts
deleted file mode 100644
index 67487aa098f4..000000000000
--- a/products/experiments/frontend/health/experimentHealthDebugLogic.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-import { MakeLogicType, connect, kea, key, path, props, selectors } from 'kea'
-
-import {
- type ExperimentLogicProps,
- type ExperimentWarning,
- experimentLogic,
- getSectionMetricUuids,
-} from 'scenes/experiments/experimentLogic'
-import { resolveMultipleVariantHandling } from 'scenes/experiments/utils'
-
-import type { ExperimentExposureCriteria } from '~/queries/schema/schema-general'
-import type { Experiment, ExperimentIdType } from '~/types'
-
-import type { ExperimentHealthApi } from '../generated/api.schemas'
-import {
- type HealthDebugCheck,
- type HealthDebugFact,
- type HealthDebugInput,
- buildHealthDebugChecks,
- buildHealthDebugFacts,
- describePanel,
- describeServerHealth,
-} from './healthDebugReport'
-import { type HealthPanelFinding, hoursSinceStart } from './healthPanelFindings'
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface experimentHealthDebugLogicValues {
- browserExperimentWarning: ExperimentWarning | null // experimentLogic
- browserNoMetricsWarning: boolean // experimentLogic
- experiment: Experiment // experimentLogic
- experimentHealth: ExperimentHealthApi | null // experimentLogic
- experimentLoadCount: number // experimentLogic
- exposureCriteria: ExperimentExposureCriteria | undefined // experimentLogic
- exposures: any // experimentLogic
- exposuresLoading: boolean // experimentLogic
- healthFindings: HealthPanelFinding[] | null // experimentLogic
- isExperimentDraft: boolean // experimentLogic
- healthDebugChecks: HealthDebugCheck[]
- healthDebugFacts: HealthDebugFact[]
- pageMetricCounts: HealthDebugInput['pageMetricCounts']
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface experimentHealthDebugLogicMeta {
- key: ExperimentIdType
- __keaTypeGenInternalSelectorTypes: {
- pageMetricCounts: (experiment: Experiment) => HealthDebugInput['pageMetricCounts']
- healthDebugChecks: (
- experiment: Experiment,
- experimentHealth: ExperimentHealthApi | null,
- healthFindings: HealthPanelFinding[] | null,
- browserExperimentWarning: ExperimentWarning | null,
- browserNoMetricsWarning: boolean,
- pageMetricCounts: {
- primary: number
- secondary: number
- },
- isExperimentDraft: boolean,
- exposures: any,
- exposuresLoading: boolean,
- exposureCriteria: ExperimentExposureCriteria | undefined
- ) => HealthDebugCheck[]
- healthDebugFacts: (
- experiment: Experiment,
- experimentHealth: ExperimentHealthApi | null,
- healthFindings: HealthPanelFinding[] | null,
- pageMetricCounts: {
- primary: number
- secondary: number
- },
- experimentLoadCount: number
- ) => HealthDebugFact[]
- }
-}
-
-export type experimentHealthDebugLogicType = MakeLogicType<
- experimentHealthDebugLogicValues,
- {},
- ExperimentLogicProps,
- experimentHealthDebugLogicMeta
->
-
-/** The staff-only view of the health checks: what each check read and why the panel shows what it shows. */
-export const experimentHealthDebugLogic = kea<experimentHealthDebugLogicType>([
- props({} as ExperimentLogicProps),
- key((props) => props.experimentId ?? 'new'),
- path((key) => ['products', 'experiments', 'health', 'experimentHealthDebugLogic', key]),
- connect((props: ExperimentLogicProps) => ({
- values: [
- experimentLogic(props),
- [
- 'experiment',
- 'experimentHealth',
- 'healthFindings',
- 'browserExperimentWarning',
- 'browserNoMetricsWarning',
- 'exposures',
- 'exposuresLoading',
- 'exposureCriteria',
- 'isExperimentDraft',
- 'experimentLoadCount',
- ],
- ],
- })),
- selectors({
- pageMetricCounts: [
- (s) => [s.experiment],
- (experiment: Experiment): HealthDebugInput['pageMetricCounts'] => ({
- primary: getSectionMetricUuids(experiment, false).length,
- secondary: getSectionMetricUuids(experiment, true).length,
- }),
- ],
- healthDebugChecks: [
- (s) => [
- s.experiment,
- s.experimentHealth,
- s.healthFindings,
- s.browserExperimentWarning,
- s.browserNoMetricsWarning,
- s.pageMetricCounts,
- s.isExperimentDraft,
- s.exposures,
- s.exposuresLoading,
- s.exposureCriteria,
- ],
- (
- experiment: Experiment,
- experimentHealth: ExperimentHealthApi | null,
- healthFindings: HealthPanelFinding[] | null,
- browserWarning: HealthDebugInput['browserWarning'],
- browserNoMetricsWarning: boolean,
- pageMetricCounts: HealthDebugInput['pageMetricCounts'],
- isExperimentDraft: boolean,
- exposures: HealthDebugInput['exposures'],
- exposuresLoading: boolean,
- exposureCriteria: ExperimentExposureCriteria | undefined
- ): HealthDebugCheck[] =>
- buildHealthDebugChecks({
- health: experimentHealth,
- panelFindings: healthFindings,
- browserWarning,
- browserNoMetricsWarning,
- pageMetricCounts,
- isExperimentDraft,
- hoursSinceStart: hoursSinceStart(experiment.start_date),
- exposures,
- exposuresLoading,
- multipleVariantHandling: resolveMultipleVariantHandling(
- exposureCriteria?.multiple_variant_handling
- ),
- }),
- ],
- healthDebugFacts: [
- (s) => [s.experiment, s.experimentHealth, s.healthFindings, s.pageMetricCounts, s.experimentLoadCount],
- (
- experiment: Experiment,
- experimentHealth: ExperimentHealthApi | null,
- healthFindings: HealthPanelFinding[] | null,
- pageMetricCounts: HealthDebugInput['pageMetricCounts'],
- experimentLoadCount: number
- ): HealthDebugFact[] => [
- { label: 'Server health', value: describeServerHealth(experimentHealth) },
- { label: 'Health panel', value: describePanel(healthFindings) },
- {
- label: 'Page load',
- value: `${experimentLoadCount}. Each finding is reported as shown once per load.`,
- },
- ...buildHealthDebugFacts(experiment, pageMetricCounts),
- ],
- ],
- }),
-])
diff --git a/products/experiments/frontend/health/healthDebugReport.ts b/products/experiments/frontend/health/healthDebugReport.ts
deleted file mode 100644
index 576a9b264f3c..000000000000
--- a/products/experiments/frontend/health/healthDebugReport.ts
+++ /dev/null
@@ -1,316 +0,0 @@
-import type { ExperimentWarning } from 'scenes/experiments/experimentLogic'
-
-import type { ExperimentExposureQueryResponse } from '~/queries/schema/schema-general'
-import type { Experiment } from '~/types'
-
-import { EXPERIMENT_VARIANT_MULTIPLE } from '../constants'
-import { getExperimentStatus } from '../experimentStatus'
-import type { ExperimentHealthApi, ExperimentHealthFindingApi } from '../generated/api.schemas'
-import { FLAG_STATE_FINDING_CODES, experimentWarningFromHealth } from './experimentHealthFindingEvents'
-import { getTotalExposures } from './exposureHealth'
-import type { HealthPanelFinding } from './healthPanelFindings'
-
-export type HealthDebugSource = 'server' | 'browser rules' | 'exposure answer'
-
-export interface HealthDebugCheck {
- check: string
- source: HealthDebugSource
- result: string
- /** The inputs behind the result, or why the check gave none. */
- note: string | null
- /** True when the browser's rules and the server's check disagree. */
- differs: boolean
-}
-
-export interface HealthDebugInput {
- health: ExperimentHealthApi | null
- panelFindings: HealthPanelFinding[] | null
- browserWarning: ExperimentWarning | null
- browserNoMetricsWarning: boolean
- pageMetricCounts: { primary: number; secondary: number }
- isExperimentDraft: boolean
- hoursSinceStart: number | null
- exposures: ExperimentExposureQueryResponse | null | undefined
- exposuresLoading: boolean
- multipleVariantHandling: 'exclude' | 'first_seen'
-}
-
-const NO_FINDING = 'no finding'
-const NOT_LOADED = 'not loaded'
-
-export function describeServerHealth(health: ExperimentHealthApi | null): string {
- return health ? `${health.findings.length} findings` : `${NOT_LOADED}: the health request is pending or failed`
-}
-
-export function describePanel(panelFindings: HealthPanelFinding[] | null): string {
- if (panelFindings === null) {
- return 'hidden: no server health, so the page shows its separate warnings'
- }
- if (panelFindings.length === 0) {
- return 'hidden: no findings'
- }
- return `shows ${panelFindings.length} findings`
-}
-
-function warningLabel(warning: ExperimentWarning | null): string {
- if (!warning) {
- return NO_FINDING
- }
- return warning.variantKey ? `${warning.key} (${warning.variantKey})` : warning.key
-}
-
-function serverResult(
- health: ExperimentHealthApi | null,
- matches: (code: ExperimentHealthFindingApi['code']) => boolean
-): string {
- if (!health) {
- return NOT_LOADED
- }
- const finding = health.findings.find((candidate) => matches(candidate.code))
- if (!finding) {
- return NO_FINDING
- }
- const variantKey = finding.evidence.variant_key
- return [finding.code, finding.subcode, typeof variantKey === 'string' ? `(${variantKey})` : null]
- .filter(Boolean)
- .join(' · ')
-}
-
-function flagStateChecks(input: HealthDebugInput): HealthDebugCheck[] {
- const serverWarning = input.health ? experimentWarningFromHealth(input.health) : null
- // A subcode the page does not know maps to no warning, so it can match a browser that finds none.
- // The raw finding still counts as a difference then.
- const hasUnmappedServerFinding =
- !serverWarning && !!input.health?.findings.some((finding) => FLAG_STATE_FINDING_CODES.has(finding.code))
- const differs =
- !!input.health &&
- (hasUnmappedServerFinding || warningLabel(serverWarning) !== warningLabel(input.browserWarning))
- return [
- {
- check: 'flag_state',
- source: 'server',
- result: serverResult(input.health, (code) => FLAG_STATE_FINDING_CODES.has(code)),
- note: null,
- differs: false,
- },
- {
- check: 'flag_state',
- source: 'browser rules',
- result: warningLabel(input.browserWarning),
- note: differs ? "Differs from the server's finding. The page shows the server's." : null,
- differs,
- },
- ]
-}
-
-function noMetricChecks(input: HealthDebugInput): HealthDebugCheck[] {
- const { primary, secondary } = input.pageMetricCounts
- const serverFires = !!input.health?.findings.some((finding) => finding.code === 'no_metric')
- const differs = !!input.health && input.browserNoMetricsWarning !== serverFires
- return [
- {
- check: 'no_metric',
- source: 'server',
- result: serverResult(input.health, (code) => code === 'no_metric'),
- note: null,
- differs: false,
- },
- {
- check: 'no_metric',
- source: 'browser rules',
- result: input.browserNoMetricsWarning ? 'no_metric' : NO_FINDING,
- note: `The page lists ${primary} primary and ${secondary} secondary metrics.${
- differs ? " Differs from the server's finding. The page shows the server's." : ''
- }`,
- differs,
- },
- ]
-}
-
-function flagVariantsChecks(input: HealthDebugInput): HealthDebugCheck[] {
- return [
- {
- check: 'flag_variants_mismatch',
- source: 'server',
- result: serverResult(input.health, (code) => code === 'flag_variants_mismatch'),
- note: null,
- differs: false,
- },
- ]
-}
-
-function forcedVariantChecks(input: HealthDebugInput): HealthDebugCheck[] {
- const finding = input.health?.findings.find(({ code }) => code === 'forced_variant_release_condition')
- return [
- {
- check: 'forced_variant_release_condition',
- source: 'server',
- result: serverResult(input.health, (code) => code === 'forced_variant_release_condition'),
- note: finding
- ? `Pinned condition sets: ${finding.evidence.pinned_condition_sets}. Variants: ${finding.evidence.pinned_variant_keys}. The users they match are not randomly assigned.`
- : null,
- differs: false,
- },
- ]
-}
-
-function splitChangedChecks(input: HealthDebugInput): HealthDebugCheck[] {
- const finding = input.health?.findings.find(({ code }) => code === 'split_changed_mid_run')
- return [
- {
- check: 'split_changed_mid_run',
- source: 'server',
- result: serverResult(input.health, (code) => code === 'split_changed_mid_run'),
- note: finding ? splitChangedNote(finding) : null,
- differs: false,
- },
- ]
-}
-
-function splitChangedNote(finding: ExperimentHealthFindingApi): string {
- const { evidence } = finding
- if (finding.subcode === 'not_checked') {
- return evidence.change_count == null
- ? `Not checked: ${evidence.reason}.`
- : `Not checked: ${evidence.reason}. ${evidence.change_count} changes since launch, from ${evidence.from} to ${evidence.to}.`
- }
- const exposedBefore = evidence.exposed_before_change
- return `${evidence.change_count} counted changes, from ${evidence.from} to ${evidence.to}. Exposed before the first: ${exposedBefore == null ? 'unknown' : exposedBefore ? 'yes' : 'no'}.`
-}
-
-function exposureChecks(input: HealthDebugInput): HealthDebugCheck[] {
- const { exposures } = input
- const panelCodes = new Set(input.panelFindings?.map((finding) => finding.code))
- const serverCodes = new Set<string>(input.health?.findings.map((finding) => finding.code))
- const skipped = input.isExperimentDraft
- ? 'skipped: the experiment is a draft'
- : !exposures
- ? input.exposuresLoading
- ? 'skipped: the exposures are loading'
- : 'skipped: no exposure answer'
- : null
-
- const result = (code: HealthPanelFinding['code']): string => {
- if (skipped) {
- return skipped
- }
- if (serverCodes.has(code)) {
- return 'not added: the server sent this code'
- }
- return panelCodes.has(code) ? code : NO_FINDING
- }
-
- const total = getTotalExposures(exposures)
- const multiple = Number(exposures?.total_exposures?.[EXPERIMENT_VARIANT_MULTIPLE] || 0)
- const pValue = exposures?.sample_ratio_mismatch?.p_value
- return [
- {
- check: 'zero_exposures',
- source: 'exposure answer',
- result: result('zero_exposures'),
- note: exposures
- ? `${total} users exposed. ${
- input.hoursSinceStart === null
- ? 'Not launched.'
- : `Started ${Math.floor(input.hoursSinceStart)} hours ago.`
- }`
- : null,
- differs: false,
- },
- {
- check: 'srm',
- source: 'exposure answer',
- result: result('srm'),
- note: exposures
- ? pValue != null
- ? `p = ${pValue.toPrecision(3)}. The finding needs p < 0.001.`
- : 'The exposure answer has no sample ratio test.'
- : null,
- differs: false,
- },
- {
- check: 'bias_risk_multiple_excluded',
- source: 'exposure answer',
- result: result('bias_risk_multiple_excluded'),
- note: exposures
- ? `${exposures.bias_risk ? `bias_risk ${exposures.bias_risk.multiple_variant_percentage.toFixed(2)}%` : 'No bias_risk in the answer'}. $multiple: ${multiple} of ${total} users. Handling: ${input.multipleVariantHandling}.`
- : null,
- differs: false,
- },
- ]
-}
-
-/** One row per check and source, so a reader can see why the health panel shows what it shows. */
-export function buildHealthDebugChecks(input: HealthDebugInput): HealthDebugCheck[] {
- return [
- ...flagStateChecks(input),
- ...splitChangedChecks(input),
- ...flagVariantsChecks(input),
- ...forcedVariantChecks(input),
- ...noMetricChecks(input),
- ...exposureChecks(input),
- ]
-}
-
-export interface HealthDebugFact {
- label: string
- value: string
-}
-
-function percentage(value: unknown): string {
- return typeof value === 'number' ? `${value}%` : 'unset'
-}
-
-/** The experiment and flag state that the server's checks read, as the browser holds it. */
-export function buildHealthDebugFacts(
- experiment: Experiment,
- pageMetricCounts: HealthDebugInput['pageMetricCounts']
-): HealthDebugFact[] {
- const flag = experiment.feature_flag
- const groups = flag?.filters?.groups ?? []
- const variants = flag?.filters?.multivariate?.variants ?? []
- const sharedMetricTypes = (experiment.saved_metrics ?? []).map(
- (link: { metadata?: { type?: string } }) => link.metadata?.type ?? 'none'
- )
- const countType = (type: string): number => sharedMetricTypes.filter((linkType) => linkType === type).length
-
- return [
- { label: 'Status', value: getExperimentStatus(experiment) },
- { label: 'Start date', value: experiment.start_date ?? 'none' },
- { label: 'End date', value: experiment.end_date ?? 'none' },
- { label: 'Archived', value: String(!!experiment.archived) },
- {
- label: 'Feature flag',
- value: flag ? `${flag.key}, active: ${flag.active}, deleted: ${!!flag.deleted}` : 'none',
- },
- {
- label: 'Release groups',
- value: groups.length
- ? groups
- .map((group) => {
- const properties = Array.isArray(group.properties) ? group.properties.length : 0
- return `${percentage(group.rollout_percentage)} with ${properties} properties`
- })
- .join('; ')
- : 'none',
- },
- {
- label: 'Variants',
- value: variants.length
- ? variants.map((variant) => `${variant.key} ${percentage(variant.rollout_percentage)}`).join(', ')
- : 'none',
- },
- {
- label: 'Single-use metrics',
- value: `${experiment.metrics?.length ?? 0} primary, ${experiment.metrics_secondary?.length ?? 0} secondary`,
- },
- {
- label: 'Shared metric links',
- value: `${countType('primary')} primary, ${countType('secondary')} secondary, ${countType('none')} without a type`,
- },
- {
- label: 'Metrics the page lists',
- value: `${pageMetricCounts.primary} primary, ${pageMetricCounts.secondary} secondary`,
- },
- ]
-}
diff --git a/products/experiments/frontend/setupInspector/sections/SdkProfileSection.tsx b/products/experiments/frontend/setupInspector/sections/SdkProfileSection.tsx
index 423a8681d8e6..a64e4901d0a9 100644
--- a/products/experiments/frontend/setupInspector/sections/SdkProfileSection.tsx
+++ b/products/experiments/frontend/setupInspector/sections/SdkProfileSection.tsx
@@ -10,13 +10,21 @@ import { SetupContextSection } from '../SetupContextSection'
import { SetupFactsTable } from '../SetupFactsTable'
import { formatCount, formatShare, formatTimestamp, formatYesNo } from '../setupInspectorUtils'
-export function SdkProfileSection({ section }: { section: ExperimentSetupSdkProfileSectionApi }): JSX.Element {
+export function SdkProfileSection({
+ section,
+ skippedMessage,
+}: {
+ section: ExperimentSetupSdkProfileSectionApi
+ /** Names why the section was skipped, when a caller skips it for another reason than a missing input. */
+ skippedMessage?: string
+}): JSX.Element {
const data = section.data
return (
<SetupContextSection
title="SDK profile"
description="Which SDKs send multivariate flag calls across the whole project, and how they evaluate flags."
status={section.status}
+ skippedMessage={skippedMessage}
>
{data && (
<>