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): run the exposure health checks on the server (#114109)

Marcel Poelker4fe64e9eb146
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 35dbecfa198d..c6fe5a67f72e 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -9084,6 +9084,13 @@
"date_range": {
"$ref": "#/definitions/DateRange"
},
+ "health_findings": {
+ "description": "Health check diagnostics that read the exposures: zero exposures, a sample ratio mismatch, and bias. Empty when every check passed.",
+ "items": {
+ "$ref": "#/definitions/ExperimentExposureHealthFinding"
+ },
+ "type": "array"
+ },
"is_cached": {
"type": "boolean"
},
@@ -25880,6 +25887,64 @@
"required": ["conversionRateInputType"],
"type": "object"
},
+ "ExperimentExposureHealthFinding": {
+ "additionalProperties": false,
+ "description": "A problem that a health check found in the exposure answer. Same shape as the experiment's `health.findings`.",
+ "properties": {
+ "actions": {
+ "description": "The actions that fix the problem, in order of preference.",
+ "items": {
+ "$ref": "#/definitions/ExperimentExposureHealthFindingActionKind"
+ },
+ "type": "array"
+ },
+ "code": {
+ "$ref": "#/definitions/ExperimentExposureHealthFindingCode",
+ "description": "Stable identifier of the problem. Each code has one meaning across every surface that reports it."
+ },
+ "detail": {
+ "description": "What is wrong, what it does to the experiment, and how to fix it.",
+ "type": "string"
+ },
+ "diagnostic_ref": {
+ "description": "The id of the matching diagnostic in the diagnosing-experiment-health skill, for example 'A2'. Null when the skill has none.",
+ "type": ["string", "null"]
+ },
+ "evidence": {
+ "additionalProperties": {
+ "type": ["string", "number", "null"]
+ },
+ "description": "The values behind the finding, such as the p-value of the sample ratio test. The keys depend on the code.",
+ "type": "object"
+ },
+ "severity": {
+ "$ref": "#/definitions/ExperimentExposureHealthFindingSeverity",
+ "description": "How much the problem affects the results: critical, warning, or info."
+ },
+ "subcode": {
+ "description": "The case within the code, when a code covers several. Null when the code has one case.",
+ "type": ["string", "null"]
+ },
+ "title": {
+ "description": "One-line summary of the problem.",
+ "type": "string"
+ }
+ },
+ "required": ["code", "subcode", "severity", "title", "detail", "evidence", "actions", "diagnostic_ref"],
+ "type": "object"
+ },
+ "ExperimentExposureHealthFindingActionKind": {
+ "enum": ["edit_exposure_criteria", "adjust_distribution", "use_first_seen_variant"],
+ "type": "string"
+ },
+ "ExperimentExposureHealthFindingCode": {
+ "enum": ["zero_exposures", "srm", "bias_risk_multiple_excluded"],
+ "type": "string"
+ },
+ "ExperimentExposureHealthFindingSeverity": {
+ "enum": ["critical", "warning", "info"],
+ "type": "string"
+ },
"ExperimentExposureNode": {
"additionalProperties": false,
"description": "Sentinel start source for retention metrics. It carries no event of its own: at query time it resolves to the experiment's exposure, so one shared metric anchors correctly on any experiment regardless of that experiment's exposure event.",
@@ -25954,6 +26019,13 @@
"date_range": {
"$ref": "#/definitions/DateRange"
},
+ "health_findings": {
+ "description": "Health check diagnostics that read the exposures: zero exposures, a sample ratio mismatch, and bias. Empty when every check passed.",
+ "items": {
+ "$ref": "#/definitions/ExperimentExposureHealthFinding"
+ },
+ "type": "array"
+ },
"kind": {
"const": "ExperimentExposureQuery",
"type": "string"
@@ -43650,6 +43722,13 @@
"date_range": {
"$ref": "#/definitions/DateRange"
},
+ "health_findings": {
+ "description": "Health check diagnostics that read the exposures: zero exposures, a sample ratio mismatch, and bias. Empty when every check passed.",
+ "items": {
+ "$ref": "#/definitions/ExperimentExposureHealthFinding"
+ },
+ "type": "array"
+ },
"kind": {
"const": "ExperimentExposureQuery",
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 9e69605c2927..d369795d559d 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -6299,6 +6299,35 @@ export interface BiasRisk {
multiple_variant_percentage: number
}
+export type ExperimentExposureHealthFindingCode = 'zero_exposures' | 'srm' | 'bias_risk_multiple_excluded'
+
+export type ExperimentExposureHealthFindingSeverity = 'critical' | 'warning' | 'info'
+
+export type ExperimentExposureHealthFindingActionKind =
+ | 'edit_exposure_criteria'
+ | 'adjust_distribution'
+ | 'use_first_seen_variant'
+
+/** A problem that a health check found in the exposure answer. Same shape as the experiment's `health.findings`. */
+export interface ExperimentExposureHealthFinding {
+ /** Stable identifier of the problem. Each code has one meaning across every surface that reports it. */
+ code: ExperimentExposureHealthFindingCode
+ /** The case within the code, when a code covers several. Null when the code has one case. */
+ subcode: string | null
+ /** How much the problem affects the results: critical, warning, or info. */
+ severity: ExperimentExposureHealthFindingSeverity
+ /** One-line summary of the problem. */
+ title: string
+ /** What is wrong, what it does to the experiment, and how to fix it. */
+ detail: string
+ /** The values behind the finding, such as the p-value of the sample ratio test. The keys depend on the code. */
+ evidence: Record<string, string | number | null>
+ /** The actions that fix the problem, in order of preference. */
+ actions: ExperimentExposureHealthFindingActionKind[]
+ /** The id of the matching diagnostic in the diagnosing-experiment-health skill, for example 'A2'. Null when the skill has none. */
+ diagnostic_ref: string | null
+}
+
export interface ExperimentExposureQueryResponse {
kind: NodeKind.ExperimentExposureQuery
timeseries: ExperimentExposureTimeSeries[]
@@ -6306,6 +6335,8 @@ export interface ExperimentExposureQueryResponse {
date_range: DateRange
sample_ratio_mismatch?: SampleRatioMismatch
bias_risk?: BiasRisk
+ /** Health check diagnostics that read the exposures: zero exposures, a sample ratio mismatch, and bias. Empty when every check passed. */
+ health_findings?: ExperimentExposureHealthFinding[]
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[]
}
diff --git a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
index 412a6f9f6fe5..93b3738d53eb 100644
--- a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
@@ -170,8 +170,8 @@ export function Exposures(): JSX.Element {
// The open panel says "No exposures yet" for a draft and after a failed exposure query too.
// Only a launched experiment with an answer that holds no exposure is the zero-exposure state.
- const hasZeroExposures =
- !isExperimentDraft && !exposuresLoading && exposures != null && !exposures.timeseries?.length
+ // The answer holds a series for every configured variant, with zero counts, so only the total tells.
+ const hasZeroExposures = !isExperimentDraft && !exposuresLoading && exposures != null && totalExposures === 0
const { reportOpened: reportSrmOpened } = useHealthFindingReporting(
hasSRM && !isExperimentDraft && !exposuresLoading ? { code: 'srm' } : null
@@ -304,7 +304,7 @@ export function Exposures(): JSX.Element {
</div>
)}
</div>
- ) : !exposures?.timeseries?.length ? (
+ ) : totalExposures === 0 ? (
<div className="relative border rounded h-[200px] flex justify-center items-center">
<div className="text-center">
<IconCorrelationAnalysis className="text-3xl mb-2 text-tertiary" />
diff --git a/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx b/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx
index cb66e6e25d3b..dc422c4a703b 100644
--- a/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx
@@ -21,7 +21,25 @@ import { MultiVariantBiasWarning } from './MultiVariantBiasWarning'
const EXPERIMENT_ID = 7
-const NO_EXPOSURES = { timeseries: [], total_exposures: {} }
+// The exposure query returns a series for every configured variant, with zero counts when nobody was exposed.
+const NO_EXPOSURES = {
+ timeseries: [
+ { variant: 'control', days: ['2026-01-01', '2026-01-02'], exposure_counts: [0, 0] },
+ { variant: 'test', days: ['2026-01-01', '2026-01-02'], exposure_counts: [0, 0] },
+ ],
+ total_exposures: { control: 0, test: 0 },
+}
+
+const exposureFinding = (code: string, title: string, actions: string[]): Record<string, unknown> => ({
+ code,
+ subcode: null,
+ severity: 'warning',
+ title,
+ detail: title,
+ evidence: {},
+ actions,
+ diagnostic_ref: null,
+})
const UNEVEN_EXPOSURES = {
timeseries: [
@@ -31,6 +49,13 @@ const UNEVEN_EXPOSURES = {
total_exposures: { control: 600, test: 400 },
sample_ratio_mismatch: { expected: { control: 500, test: 500 }, p_value: 0.0001 },
bias_risk: { multiple_variant_percentage: 5 },
+ health_findings: [
+ exposureFinding('srm', 'Users are not split across variants as configured', []),
+ exposureFinding('bias_risk_multiple_excluded', 'Setup likely introduced bias', [
+ 'adjust_distribution',
+ 'use_first_seen_variant',
+ ]),
+ ],
}
describe('health finding reporting', () => {
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 93fa6df4a960..8ff4f409cc5e 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -96,11 +96,7 @@ import {
experimentWarningFromHealth,
exposureHealthEventProperties,
} from 'products/experiments/frontend/health/experimentHealthFindingEvents'
-import {
- type HealthPanelFinding,
- healthPanelFindings,
- hoursSinceStart,
-} from 'products/experiments/frontend/health/healthPanelFindings'
+import { type HealthPanelFinding, healthPanelFindings } from 'products/experiments/frontend/health/healthPanelFindings'
import {
legacyExpectedRunningTime,
legacyMinimumSampleSizePerVariant,
@@ -3898,11 +3894,7 @@ export const experimentLogic = kea<experimentLogicType>([
healthFindings: [
(s) => [s.experiment, s.exposures, s.isExperimentDraft],
(experiment: Experiment, exposures: any, isExperimentDraft: boolean): HealthPanelFinding[] | null =>
- healthPanelFindings(experiment.health, {
- exposures,
- isExperimentDraft,
- hoursSinceStart: hoursSinceStart(experiment.start_date),
- }),
+ healthPanelFindings(experiment.health, exposures, isExperimentDraft),
],
firstPrimaryMetric: [
(s) => [s.experiment],
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithHealthFindings.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithHealthFindings.stories.tsx
index 6e4331464256..cff594b56bbf 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithHealthFindings.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithHealthFindings.stories.tsx
@@ -34,6 +34,28 @@ const EXPOSURES_WITH_BIAS_RISK = {
...EXPOSURE_QUERY_RESULT,
sample_ratio_mismatch: { expected: { control: 1000, 'test-1': 1000, 'test-2': 1000 }, p_value: 0.0001 },
bias_risk: { multiple_variant_percentage: 4.2 },
+ health_findings: [
+ {
+ code: 'srm',
+ subcode: null,
+ severity: 'warning',
+ title: 'Users are not split across variants as configured',
+ detail: "The distribution of users across variants doesn't match your configured rollout percentages (p < 0.001). This may indicate issues with randomization or data collection.",
+ evidence: { p_value: 0.0001 },
+ actions: [],
+ diagnostic_ref: 'A2',
+ },
+ {
+ code: 'bias_risk_multiple_excluded',
+ subcode: null,
+ severity: 'warning',
+ title: 'Setup likely introduced bias',
+ detail: '4.2% of users were exposed to multiple variants. With an uneven variant split and the Exclude handling, these users were dropped more often from the smaller variant, so its metrics can be biased. Use an even split and control exposure with the overall rollout, or switch the handling to First seen.',
+ evidence: { multiple_variant_percentage: 4.2 },
+ actions: ['adjust_distribution', 'use_first_seen_variant'],
+ diagnostic_ref: 'A1',
+ },
+ ],
}
const meta: Meta = {
diff --git a/posthog/schema.py b/posthog/schema.py
index 6dd039d82772..46b98e0ef474 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -122,6 +122,9 @@ from posthog.schema_enums import (
EventMatchScope as EventMatchScope,
ExperimentApiBreakdownAttributionType as ExperimentApiBreakdownAttributionType,
ExperimentApiPropertyBreakdownType as ExperimentApiPropertyBreakdownType,
+ ExperimentExposureHealthFindingActionKind as ExperimentExposureHealthFindingActionKind,
+ ExperimentExposureHealthFindingCode as ExperimentExposureHealthFindingCode,
+ ExperimentExposureHealthFindingSeverity as ExperimentExposureHealthFindingSeverity,
ExperimentMetricGoal as ExperimentMetricGoal,
ExperimentMetricMathType as ExperimentMetricMathType,
ExperimentMetricType as ExperimentMetricType,
@@ -5708,12 +5711,60 @@ class ExperimentApiRetentionStart(BaseModel):
)
+class ExperimentExposureHealthFinding(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ actions: list[ExperimentExposureHealthFindingActionKind] = Field(
+ ..., description="The actions that fix the problem, in order of preference."
+ )
+ code: ExperimentExposureHealthFindingCode = Field(
+ ...,
+ description=(
+ "Stable identifier of the problem. Each code has one meaning across every surface that reports it."
+ ),
+ )
+ detail: str = Field(
+ ...,
+ description="What is wrong, what it does to the experiment, and how to fix it.",
+ )
+ diagnostic_ref: str | None = Field(
+ ...,
+ description=(
+ "The id of the matching diagnostic in the diagnosing-experiment-health"
+ " skill, for example 'A2'. Null when the skill has none."
+ ),
+ )
+ evidence: dict[str, str | float | None] = Field(
+ ...,
+ description=(
+ "The values behind the finding, such as the p-value of the sample ratio test. The keys depend on the code."
+ ),
+ )
+ severity: ExperimentExposureHealthFindingSeverity = Field(
+ ...,
+ description=("How much the problem affects the results: critical, warning, or info."),
+ )
+ subcode: str | None = Field(
+ ...,
+ description=("The case within the code, when a code covers several. Null when the code has one case."),
+ )
+ title: str = Field(..., description="One-line summary of the problem.")
+
+
class ExperimentExposureQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
bias_risk: BiasRisk | None = None
date_range: DateRange
+ health_findings: list[ExperimentExposureHealthFinding] | None = Field(
+ default=None,
+ description=(
+ "Health check diagnostics that read the exposures: zero exposures, a sample"
+ " ratio mismatch, and bias. Empty when every check passed."
+ ),
+ )
kind: Literal["ExperimentExposureQuery"] = "ExperimentExposureQuery"
sample_ratio_mismatch: SampleRatioMismatch | None = None
timeseries: list[ExperimentExposureTimeSeries]
@@ -7256,6 +7307,13 @@ class QueryResponseAlternative21(BaseModel):
)
bias_risk: BiasRisk | None = None
date_range: DateRange
+ health_findings: list[ExperimentExposureHealthFinding] | None = Field(
+ default=None,
+ description=(
+ "Health check diagnostics that read the exposures: zero exposures, a sample"
+ " ratio mismatch, and bias. Empty when every check passed."
+ ),
+ )
kind: Literal["ExperimentExposureQuery"] = "ExperimentExposureQuery"
sample_ratio_mismatch: SampleRatioMismatch | None = None
timeseries: list[ExperimentExposureTimeSeries]
@@ -12410,6 +12468,13 @@ class CachedExperimentExposureQueryResponse(BaseModel):
description=("What triggered the calculation of the query, leave empty if user/immediate"),
)
date_range: DateRange
+ health_findings: list[ExperimentExposureHealthFinding] | None = Field(
+ default=None,
+ description=(
+ "Health check diagnostics that read the exposures: zero exposures, a sample"
+ " ratio mismatch, and bias. Empty when every check passed."
+ ),
+ )
is_cached: bool
kind: Literal["ExperimentExposureQuery"] = "ExperimentExposureQuery"
last_refresh: AwareDatetime
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 9c1ba21f597b..e7daa2e7bfa5 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1409,6 +1409,24 @@ class ManualMetricType(StrEnum):
MEAN_SUM_OR_AVG = "mean_sum_or_avg"
+class ExperimentExposureHealthFindingActionKind(StrEnum):
+ EDIT_EXPOSURE_CRITERIA = "edit_exposure_criteria"
+ ADJUST_DISTRIBUTION = "adjust_distribution"
+ USE_FIRST_SEEN_VARIANT = "use_first_seen_variant"
+
+
+class ExperimentExposureHealthFindingCode(StrEnum):
+ ZERO_EXPOSURES = "zero_exposures"
+ SRM = "srm"
+ BIAS_RISK_MULTIPLE_EXCLUDED = "bias_risk_multiple_excluded"
+
+
+class ExperimentExposureHealthFindingSeverity(StrEnum):
+ CRITICAL = "critical"
+ WARNING = "warning"
+ INFO = "info"
+
+
class ExperimentMetricGoal(StrEnum):
INCREASE = "increase"
DECREASE = "decrease"
diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.py
index 1492d157b737..0c700f5f3359 100644
--- a/products/experiments/backend/facade/api.py
+++ b/products/experiments/backend/facade/api.py
@@ -14,7 +14,10 @@ from posthog.models.user import User
from products.experiments.backend.experiment_service import ExperimentService
from products.experiments.backend.health.context import load_health_context
-from products.experiments.backend.health.registry import evaluate as evaluate_health
+from products.experiments.backend.health.registry import (
+ EXPERIMENT_HEALTH_CHECKS,
+ evaluate as evaluate_health,
+)
from products.experiments.backend.hogql_queries.exposure_query_logic import (
DEFAULT_EXPOSURE_EVENT,
get_exposure_event_and_property,
@@ -130,7 +133,7 @@ def get_experiment_health_findings(*, team_id: int, experiment_id: int) -> list[
.prefetch_related("experimenttosavedmetric_set")
.get(id=experiment_id)
)
- return evaluate_health(load_health_context(experiment))
+ return evaluate_health(load_health_context(experiment), EXPERIMENT_HEALTH_CHECKS)
def _experiment_model_to_dto(experiment: ExperimentModel) -> Experiment:
diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.py
index b04f7c39cc65..f5b5c15fa14a 100644
--- a/products/experiments/backend/facade/contracts.py
+++ b/products/experiments/backend/facade/contracts.py
@@ -104,6 +104,8 @@ class ExperimentHealthFindingCode(LabeledStrEnum):
FLAG_LIVE_BEFORE_LAUNCH = "flag_live_before_launch"
BIAS_RISK_MULTIPLE_EXCLUDED = "bias_risk_multiple_excluded"
NO_METRIC = "no_metric"
+ SRM = "srm", "Sample Ratio Mismatch"
+ ZERO_EXPOSURES = "zero_exposures"
class ExperimentHealthFindingSeverity(LabeledStrEnum):
@@ -121,6 +123,7 @@ class ExperimentHealthFindingActionKind(LabeledStrEnum):
USE_FIRST_SEEN_VARIANT = "use_first_seen_variant"
ADD_PRIMARY_METRIC = "add_primary_metric"
ADD_SECONDARY_METRIC = "add_secondary_metric"
+ EDIT_EXPOSURE_CRITERIA = "edit_exposure_criteria"
@frozen
diff --git a/products/experiments/backend/health/checks/srm.py b/products/experiments/backend/health/checks/srm.py
new file mode 100644
index 000000000000..8aecf128b59c
--- /dev/null
+++ b/products/experiments/backend/health/checks/srm.py
@@ -0,0 +1,27 @@
+from products.experiments.backend.facade.contracts import (
+ ExperimentHealthFinding,
+ ExperimentHealthFindingCode,
+ ExperimentHealthFindingSeverity,
+)
+from products.experiments.backend.health.context import HealthContext
+
+SAMPLE_RATIO_MISMATCH_P_VALUE = 0.001
+
+
+def srm(ctx: HealthContext) -> ExperimentHealthFinding | None:
+ p_value = ctx.exposures.sample_ratio_mismatch_p_value if ctx.exposures else None
+ if p_value is None or p_value >= SAMPLE_RATIO_MISMATCH_P_VALUE:
+ return None
+ return ExperimentHealthFinding(
+ code=ExperimentHealthFindingCode.SRM,
+ subcode=None,
+ severity=ExperimentHealthFindingSeverity.WARNING,
+ title="Users are not split across variants as configured",
+ detail=(
+ "The distribution of users across variants doesn't match your configured rollout percentages "
+ f"(p < {SAMPLE_RATIO_MISMATCH_P_VALUE}). This may indicate issues with randomization or data collection."
+ ),
+ evidence={"p_value": p_value},
+ actions=(),
+ diagnostic_ref="A2",
+ )
diff --git a/products/experiments/backend/health/checks/zero_exposures.py b/products/experiments/backend/health/checks/zero_exposures.py
new file mode 100644
index 000000000000..71a80da6bf33
--- /dev/null
+++ b/products/experiments/backend/health/checks/zero_exposures.py
@@ -0,0 +1,32 @@
+from products.experiments.backend.facade.contracts import (
+ ExperimentHealthFinding,
+ ExperimentHealthFindingActionKind,
+ ExperimentHealthFindingCode,
+ ExperimentHealthFindingSeverity,
+)
+from products.experiments.backend.health.context import HealthContext
+
+# A new experiment often has no exposure in its first hours, so the finding waits as long as the experiments scout does.
+ZERO_EXPOSURES_GRACE_HOURS = 24
+
+
+def zero_exposures(ctx: HealthContext) -> ExperimentHealthFinding | None:
+ exposures = ctx.exposures
+ if exposures is None or exposures.hours_since_launch is None or not ctx.is_launched:
+ return None
+ if exposures.hours_since_launch < ZERO_EXPOSURES_GRACE_HOURS or sum(exposures.total_exposures.values()) > 0:
+ return None
+ return ExperimentHealthFinding(
+ code=ExperimentHealthFindingCode.ZERO_EXPOSURES,
+ subcode=None,
+ severity=ExperimentHealthFindingSeverity.WARNING,
+ title="No users exposed",
+ detail=(
+ "No users have been exposed to this experiment, so it shows no results. "
+ "Users are counted when the exposure event is sent for them. Check that your code evaluates "
+ "the linked feature flag and that the exposure criteria match the events you send."
+ ),
+ evidence={"hours_since_launch": int(exposures.hours_since_launch)},
+ actions=(ExperimentHealthFindingActionKind.EDIT_EXPOSURE_CRITERIA,),
+ diagnostic_ref=None,
+ )
diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.py
index 0bcb674db24a..9949a221ddfd 100644
--- a/products/experiments/backend/health/context.py
+++ b/products/experiments/backend/health/context.py
@@ -32,6 +32,9 @@ class FlagState:
class ExposureTotals:
total_exposures: Mapping[str, int]
multiple_variant_handling: MultipleVariantHandling
+ # None when the exposure query had too little data for the sample ratio test.
+ sample_ratio_mismatch_p_value: float | None
+ hours_since_launch: float | None
@frozen
diff --git a/products/experiments/backend/health/registry.py b/products/experiments/backend/health/registry.py
index 6736f9eff150..90b15f95885a 100644
--- a/products/experiments/backend/health/registry.py
+++ b/products/experiments/backend/health/registry.py
@@ -1,4 +1,4 @@
-from collections.abc import Callable
+from collections.abc import Callable, Sequence
from posthog.exceptions_capture import capture_exception
@@ -6,17 +6,23 @@ from products.experiments.backend.facade.contracts import ExperimentHealthFindin
from products.experiments.backend.health.checks.bias_risk import bias_risk_multiple_excluded
from products.experiments.backend.health.checks.flag_state import flag_state
from products.experiments.backend.health.checks.no_metric import no_metric
+from products.experiments.backend.health.checks.srm import srm
+from products.experiments.backend.health.checks.zero_exposures import zero_exposures
from products.experiments.backend.health.context import HealthContext
HealthCheck = Callable[[HealthContext], ExperimentHealthFinding | None]
-HEALTH_CHECKS: tuple[HealthCheck, ...] = (flag_state, no_metric, bias_risk_multiple_excluded)
+EXPERIMENT_HEALTH_CHECKS: tuple[HealthCheck, ...] = (flag_state, no_metric)
+# The exposure query runs these on its answer. They must not include the checks above: the exposure answer
+# is cached for a day, and a flag edit would not clear their findings.
+EXPOSURE_HEALTH_CHECKS: tuple[HealthCheck, ...] = (zero_exposures, srm, bias_risk_multiple_excluded)
-def evaluate(ctx: HealthContext) -> list[ExperimentHealthFinding]:
- """Runs every registered check. A check returns None when the context lacks an input it reads."""
+
+def evaluate(ctx: HealthContext, checks: Sequence[HealthCheck]) -> list[ExperimentHealthFinding]:
+ """Runs the given checks. A check returns None when the context lacks an input it reads."""
findings: list[ExperimentHealthFinding] = []
- for check in HEALTH_CHECKS:
+ for check in checks:
try:
finding = check(ctx)
except Exception as error:
diff --git a/products/experiments/backend/health/test/test_registry.py b/products/experiments/backend/health/test/test_registry.py
index f69dbb1ca03d..a6b76bcb3612 100644
--- a/products/experiments/backend/health/test/test_registry.py
+++ b/products/experiments/backend/health/test/test_registry.py
@@ -12,7 +12,14 @@ from products.experiments.backend.facade.contracts import ExperimentHealthFindin
from products.experiments.backend.health import registry
from products.experiments.backend.health.checks.bias_risk import bias_risk_multiple_excluded
from products.experiments.backend.health.context import ExposureTotals, FlagState, FlagVariant, HealthContext
-from products.experiments.backend.health.registry import evaluate
+from products.experiments.backend.health.registry import EXPOSURE_HEALTH_CHECKS, evaluate
+
+UNEVEN_SPLIT_TOTALS = ExposureTotals(
+ total_exposures={"control": 800, "test": 200, "$multiple": 20},
+ multiple_variant_handling=MultipleVariantHandling.EXCLUDE,
+ sample_ratio_mismatch_p_value=None,
+ hours_since_launch=72,
+)
RUNNING_UNEVEN_SPLIT = HealthContext(
is_launched=True,
@@ -29,40 +36,59 @@ RUNNING_UNEVEN_SPLIT = HealthContext(
),
primary_metric_count=1,
secondary_metric_count=0,
- exposures=ExposureTotals(
- total_exposures={"control": 800, "test": 200, "$multiple": 20},
- multiple_variant_handling=MultipleVariantHandling.EXCLUDE,
- ),
+ exposures=UNEVEN_SPLIT_TOTALS,
)
+NO_EXPOSURES = replace(UNEVEN_SPLIT_TOTALS, total_exposures={"control": 0, "test": 0})
+
def _raise(_ctx: HealthContext) -> Any:
raise ValueError("malformed")
class TestEvaluate(TestCase):
- def test_reports_bias_risk_from_exposure_totals(self) -> None:
- findings = evaluate(RUNNING_UNEVEN_SPLIT)
-
- self.assertEqual(
- [finding.code for finding in findings], [ExperimentHealthFindingCode.BIAS_RISK_MULTIPLE_EXCLUDED]
- )
-
@parameterized.expand(
[
- ("without_exposure_totals", {"exposures": None}),
- ("after_the_end", {"has_ended": True}),
+ ("bias_risk_on_an_uneven_split", {}, [ExperimentHealthFindingCode.BIAS_RISK_MULTIPLE_EXCLUDED]),
+ ("nothing_without_exposure_totals", {"exposures": None}, []),
+ ("no_bias_risk_after_the_end", {"has_ended": True}, []),
+ (
+ "srm_below_the_threshold",
+ {"has_ended": True, "exposures": replace(UNEVEN_SPLIT_TOTALS, sample_ratio_mismatch_p_value=0.0009)},
+ [ExperimentHealthFindingCode.SRM],
+ ),
+ (
+ "no_srm_at_the_threshold",
+ {"has_ended": True, "exposures": replace(UNEVEN_SPLIT_TOTALS, sample_ratio_mismatch_p_value=0.001)},
+ [],
+ ),
+ (
+ "zero_exposures_a_day_after_launch",
+ {"exposures": replace(NO_EXPOSURES, hours_since_launch=24)},
+ [ExperimentHealthFindingCode.ZERO_EXPOSURES],
+ ),
+ ("no_zero_exposures_in_the_first_day", {"exposures": replace(NO_EXPOSURES, hours_since_launch=23.9)}, []),
+ ("no_zero_exposures_before_launch", {"is_launched": False, "exposures": NO_EXPOSURES}, []),
+ (
+ "no_zero_exposures_with_only_multiple_variant_users",
+ {
+ "has_ended": True,
+ "exposures": replace(NO_EXPOSURES, total_exposures={"control": 0, "test": 0, "$multiple": 3}),
+ },
+ [],
+ ),
]
)
- def test_no_bias_risk_finding(self, _name: str, changes: dict[str, Any]) -> None:
- codes = [finding.code for finding in evaluate(replace(RUNNING_UNEVEN_SPLIT, **changes))]
+ def test_exposure_checks(
+ self, _name: str, changes: dict[str, Any], expected: list[ExperimentHealthFindingCode]
+ ) -> None:
+ findings = evaluate(replace(RUNNING_UNEVEN_SPLIT, **changes), EXPOSURE_HEALTH_CHECKS)
- self.assertNotIn(ExperimentHealthFindingCode.BIAS_RISK_MULTIPLE_EXCLUDED, codes)
+ self.assertEqual([finding.code for finding in findings], expected)
def test_a_failing_check_does_not_hide_the_other_findings(self) -> None:
- checks = (_raise, bias_risk_multiple_excluded)
- with patch.object(registry, "HEALTH_CHECKS", checks), patch.object(registry, "capture_exception") as capture:
- findings = evaluate(RUNNING_UNEVEN_SPLIT)
+ with patch.object(registry, "capture_exception") as capture:
+ findings = evaluate(RUNNING_UNEVEN_SPLIT, (_raise, bias_risk_multiple_excluded))
self.assertEqual(
[finding.code for finding in findings], [ExperimentHealthFindingCode.BIAS_RISK_MULTIPLE_EXCLUDED]
diff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
index e82915a8e1cd..bd4e1fe7ea9b 100644
--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
@@ -9,10 +9,15 @@ from posthog.schema import (
BiasRisk,
CachedExperimentExposureQueryResponse,
DateRange,
+ ExperimentExposureHealthFinding,
+ ExperimentExposureHealthFindingActionKind,
+ ExperimentExposureHealthFindingCode,
+ ExperimentExposureHealthFindingSeverity,
ExperimentExposureQuery,
ExperimentExposureQueryResponse,
ExperimentExposureTimeSeries,
IntervalType,
+ MultipleVariantHandling,
SampleRatioMismatch,
)
@@ -28,6 +33,11 @@ from posthog.models.team.extensions import get_or_create_team_extension
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
from products.experiments.backend.health.checks.bias_risk import evaluate_bias_risk
+from products.experiments.backend.health.context import ExposureTotals, load_health_context
+from products.experiments.backend.health.registry import (
+ EXPOSURE_HEALTH_CHECKS,
+ evaluate as evaluate_health,
+)
from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY
from products.experiments.backend.hogql_queries.base_query_utils import analysis_window, analysis_window_end
from products.experiments.backend.hogql_queries.error_handling import experiment_error_handler
@@ -254,7 +264,9 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
p_value=float(p_value),
)
- def _evaluate_bias_risk(self, total_exposures: dict[str, int]) -> BiasRisk | None:
+ def _evaluate_bias_risk(
+ self, total_exposures: dict[str, int], multiple_variant_handling: MultipleVariantHandling
+ ) -> BiasRisk | None:
# Shipping a variant rewrites the flag to 100/0, which would falsely trip the
# uneven-split check on data collected under the original split. The warning also has
# no action after the experiment stops, because both of its CTAs only apply while it runs.
@@ -264,15 +276,32 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
return None
multivariate_data = (self.query.feature_flag.get("filters") or {}).get("multivariate") or {}
flag_variants = multivariate_data.get("variants") or []
- exposure_params = get_exposure_config_params_for_builder(
- self.exposure_criteria, self.team, self.experiment.start_date
- )
return evaluate_bias_risk(
rollout_percentages=[variant.get("rollout_percentage", 0) for variant in flag_variants],
- multiple_variant_handling=exposure_params.multiple_variant_handling,
+ multiple_variant_handling=multiple_variant_handling,
total_exposures=total_exposures,
)
+ def _hours_since_launch(self) -> float | None:
+ start_date = self.experiment.start_date
+ return (datetime.now(UTC) - start_date).total_seconds() / 3600 if start_date else None
+
+ def _evaluate_health(self, exposures: ExposureTotals) -> list[ExperimentExposureHealthFinding]:
+ findings = evaluate_health(load_health_context(self.experiment, exposures), EXPOSURE_HEALTH_CHECKS)
+ return [
+ ExperimentExposureHealthFinding(
+ code=ExperimentExposureHealthFindingCode(finding.code.value),
+ subcode=finding.subcode,
+ severity=ExperimentExposureHealthFindingSeverity(finding.severity.value),
+ title=finding.title,
+ detail=finding.detail,
+ evidence=dict(finding.evidence),
+ actions=[ExperimentExposureHealthFindingActionKind(action.value) for action in finding.actions],
+ diagnostic_ref=finding.diagnostic_ref,
+ )
+ for finding in findings
+ ]
+
@experiment_error_handler
def _calculate(self) -> ExperimentExposureQueryResponse:
tag_queries(
@@ -337,8 +366,19 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
for variant, series in variant_series.items():
total_exposures[variant] = int(series.exposure_counts[-1]) if series.exposure_counts else 0
+ multiple_variant_handling = get_exposure_config_params_for_builder(
+ self.exposure_criteria, self.team, self.experiment.start_date
+ ).multiple_variant_handling
sample_ratio_mismatch = self._calculate_srm(total_exposures)
- bias_risk = self._evaluate_bias_risk(total_exposures)
+ bias_risk = self._evaluate_bias_risk(total_exposures, multiple_variant_handling)
+ health_findings = self._evaluate_health(
+ ExposureTotals(
+ total_exposures=total_exposures,
+ multiple_variant_handling=multiple_variant_handling,
+ sample_ratio_mismatch_p_value=sample_ratio_mismatch.p_value if sample_ratio_mismatch else None,
+ hours_since_launch=self._hours_since_launch(),
+ )
+ )
return ExperimentExposureQueryResponse(
timeseries=ordered_timeseries,
@@ -346,6 +386,7 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
date_range=self.date_range,
sample_ratio_mismatch=sample_ratio_mismatch,
bias_risk=bias_risk,
+ health_findings=health_findings,
)
def to_query(self) -> ast.SelectQuery:
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py
index 673157bffb2e..17edc60c8598 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py
@@ -11,7 +11,13 @@ from django.test import override_settings
from parameterized import parameterized
from rest_framework.exceptions import ValidationError
-from posthog.schema import ActionsNode, ExperimentEventExposureConfig, ExperimentExposureQuery
+from posthog.schema import (
+ ActionsNode,
+ ExperimentEventExposureConfig,
+ ExperimentExposureHealthFindingCode,
+ ExperimentExposureQuery,
+ MultipleVariantHandling,
+)
from posthog.test.test_journeys import journeys_for
@@ -1465,11 +1471,39 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
# With 90/10 split on a 50/50 expected, p-value should be very low
# (well below the 0.001 threshold for SRM detection)
self.assertLess(response.sample_ratio_mismatch.p_value, 0.001)
+ self.assertEqual(
+ [finding.code for finding in response.health_findings or []], [ExperimentExposureHealthFindingCode.SRM]
+ )
# Expected counts should be 50/50 of total (100)
self.assertEqual(response.sample_ratio_mismatch.expected["control"], 50.0)
self.assertEqual(response.sample_ratio_mismatch.expected["test"], 50.0)
+ @parameterized.expand(
+ [
+ ("first_day", "2024-01-01T23:00:00Z", []),
+ ("after_a_day", "2024-01-02T01:00:00Z", [ExperimentExposureHealthFindingCode.ZERO_EXPOSURES]),
+ ]
+ )
+ def test_zero_exposures_finding_waits_a_day_after_launch(
+ self, _name: str, now: str, expected_codes: list[ExperimentExposureHealthFindingCode]
+ ) -> None:
+ query = ExperimentExposureQuery(
+ kind="ExperimentExposureQuery",
+ experiment_id=self.experiment.id,
+ experiment_name=self.experiment.name,
+ feature_flag=model_to_dict(self.feature_flag),
+ start_date=self.experiment.start_date.isoformat(),
+ end_date=None,
+ exposure_criteria=self.experiment.exposure_criteria,
+ )
+
+ with time_machine.travel(now, tick=False):
+ response = ExperimentExposuresQueryRunner(team=self.team, query=query).calculate()
+
+ self.assertEqual(response.total_exposures, {"control": 0, "test": 0})
+ self.assertEqual([finding.code for finding in response.health_findings or []], expected_codes)
+
@parameterized.expand([("direct", False), ("precomputed", True)])
@time_machine.travel("2024-01-07T12:00:00Z", tick=False)
def test_srm_returns_none_when_insufficient_samples(self, _name, use_precomputation):
@@ -1822,10 +1856,14 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):
# The running/stopped decision is read from the query, not the model — the experiment row is
# left ended throughout. Query end_date set -> reads as stopped, warning skipped.
- self.assertIsNone(_runner(experiment.end_date.isoformat())._evaluate_bias_risk(total_exposures))
+ self.assertIsNone(
+ _runner(experiment.end_date.isoformat())._evaluate_bias_risk(
+ total_exposures, MultipleVariantHandling.EXCLUDE
+ )
+ )
# Query end_date cleared -> reads as running, warning evaluated.
- risk = _runner(None)._evaluate_bias_risk(total_exposures)
+ risk = _runner(None)._evaluate_bias_risk(total_exposures, MultipleVariantHandling.EXCLUDE)
assert risk is not None
self.assertGreater(risk.multiple_variant_percentage, 0)
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 4d322b8ddc71..8845c7cd8eaa 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2268,6 +2268,8 @@ export type _ExperimentApiMetricsListApi = ExperimentApiMetricApi[]
* * `flag_live_before_launch` - Flag Live Before Launch
* * `bias_risk_multiple_excluded` - Bias Risk Multiple Excluded
* * `no_metric` - No Metric
+ * * `srm` - Sample Ratio Mismatch
+ * * `zero_exposures` - Zero Exposures
*/
export type ExperimentHealthFindingCodeEnumApi =
(typeof ExperimentHealthFindingCodeEnumApi)[keyof typeof ExperimentHealthFindingCodeEnumApi]
@@ -2279,6 +2281,8 @@ export const ExperimentHealthFindingCodeEnumApi = {
FlagLiveBeforeLaunch: 'flag_live_before_launch',
BiasRiskMultipleExcluded: 'bias_risk_multiple_excluded',
NoMetric: 'no_metric',
+ Srm: 'srm',
+ ZeroExposures: 'zero_exposures',
} as const
/**
@@ -2301,6 +2305,7 @@ export const ExperimentHealthFindingSeverityEnumApi = {
* * `use_first_seen_variant` - Use First Seen Variant
* * `add_primary_metric` - Add Primary Metric
* * `add_secondary_metric` - Add Secondary Metric
+ * * `edit_exposure_criteria` - Edit Exposure Criteria
*/
export type ExperimentHealthFindingActionKindEnumApi =
(typeof ExperimentHealthFindingActionKindEnumApi)[keyof typeof ExperimentHealthFindingActionKindEnumApi]
@@ -2311,6 +2316,7 @@ export const ExperimentHealthFindingActionKindEnumApi = {
UseFirstSeenVariant: 'use_first_seen_variant',
AddPrimaryMetric: 'add_primary_metric',
AddSecondaryMetric: 'add_secondary_metric',
+ EditExposureCriteria: 'edit_exposure_criteria',
} as const
/**
@@ -2326,7 +2332,9 @@ export interface ExperimentHealthFindingApi {
* * `flag_live_after_end` - Flag Live After End
* * `flag_live_before_launch` - Flag Live Before Launch
* * `bias_risk_multiple_excluded` - Bias Risk Multiple Excluded
- * * `no_metric` - No Metric */
+ * * `no_metric` - No Metric
+ * * `srm` - Sample Ratio Mismatch
+ * * `zero_exposures` - Zero Exposures */
code: ExperimentHealthFindingCodeEnumApi
/**
* The case within the code, when a code covers several, for example 'running_but_no_rollout' within 'flag_off_while_running'. Null when the code has one case.
diff --git a/products/experiments/frontend/health/healthDebugReport.ts b/products/experiments/frontend/health/healthDebugReport.ts
index ef26626bb686..903854d60131 100644
--- a/products/experiments/frontend/health/healthDebugReport.ts
+++ b/products/experiments/frontend/health/healthDebugReport.ts
@@ -8,7 +8,7 @@ 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, ZERO_EXPOSURES_GRACE_HOURS } from './healthPanelFindings'
+import type { HealthPanelFinding } from './healthPanelFindings'
export type HealthDebugSource = 'server' | 'browser rules' | 'exposure answer'
@@ -167,7 +167,7 @@ function exposureChecks(input: HealthDebugInput): HealthDebugCheck[] {
? `${total} users exposed. ${
input.hoursSinceStart === null
? 'Not launched.'
- : `Started ${Math.floor(input.hoursSinceStart)} hours ago. The finding waits ${ZERO_EXPOSURES_GRACE_HOURS} hours.`
+ : `Started ${Math.floor(input.hoursSinceStart)} hours ago.`
}`
: null,
differs: false,
@@ -197,18 +197,7 @@ function exposureChecks(input: HealthDebugInput): HealthDebugCheck[] {
/** 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),
- ...noMetricChecks(input),
- {
- check: 'bias_risk_multiple_excluded',
- source: 'server',
- result: serverResult(input.health, (code) => code === 'bias_risk_multiple_excluded'),
- note: null,
- differs: false,
- },
- ...exposureChecks(input),
- ]
+ return [...flagStateChecks(input), ...noMetricChecks(input), ...exposureChecks(input)]
}
export interface HealthDebugFact {
diff --git a/products/experiments/frontend/health/healthPanelFindings.test.ts b/products/experiments/frontend/health/healthPanelFindings.test.ts
index 932c2f4fd696..9747f692529c 100644
--- a/products/experiments/frontend/health/healthPanelFindings.test.ts
+++ b/products/experiments/frontend/health/healthPanelFindings.test.ts
@@ -1,5 +1,12 @@
+import {
+ type ExperimentExposureHealthFinding,
+ type ExperimentExposureHealthFindingCode,
+ type ExperimentExposureQueryResponse,
+ NodeKind,
+} from '~/queries/schema/schema-general'
+
import type { ExperimentHealthApi, ExperimentHealthFindingApi } from '../generated/api.schemas'
-import { type ExposureHealthInput, healthPanelFindings } from './healthPanelFindings'
+import { healthPanelFindings } from './healthPanelFindings'
const serverFinding = (code: ExperimentHealthFindingApi['code']): ExperimentHealthFindingApi => ({
code,
@@ -12,26 +19,34 @@ const serverFinding = (code: ExperimentHealthFindingApi['code']): ExperimentHeal
diagnostic_ref: null,
})
-// The exposure query returns a series for every configured variant, with zero counts when nobody was exposed.
-const NO_EXPOSURES = {
- timeseries: [{ variant: 'control' }, { variant: 'test' }],
- total_exposures: { control: 0, test: 0 },
-}
+const exposureFinding = (code: ExperimentExposureHealthFindingCode): ExperimentExposureHealthFinding => ({
+ code,
+ subcode: null,
+ severity: 'warning',
+ title: code,
+ detail: code,
+ evidence: {},
+ actions: [],
+ diagnostic_ref: null,
+})
const UNEVEN_EXPOSURES = {
- timeseries: [{ variant: 'control' }, { variant: 'test' }],
+ kind: NodeKind.ExperimentExposureQuery,
+ timeseries: [
+ { variant: 'control', days: ['2026-10-01', '2026-10-02'], exposure_counts: [300, 600] },
+ { variant: 'test', days: ['2026-10-01', '2026-10-02'], exposure_counts: [200, 400] },
+ ],
total_exposures: { control: 600, test: 400 },
- sample_ratio_mismatch: { expected: { control: 500, test: 500 }, p_value: 0.0001 },
- bias_risk: { multiple_variant_percentage: 5 },
-}
+ date_range: { date_from: '2026-10-01', date_to: '2026-10-02' },
+ health_findings: [exposureFinding('srm'), exposureFinding('bias_risk_multiple_excluded')],
+} satisfies ExperimentExposureQueryResponse
describe('healthPanelFindings', () => {
test.each<{
name: string
health: ExperimentHealthApi | null
- exposures: Record<string, unknown> | null
+ exposures: ExperimentExposureQueryResponse | null
isExperimentDraft: boolean
- hoursSinceStart: number | null
expected: string[] | null
}>([
{
@@ -39,7 +54,6 @@ describe('healthPanelFindings', () => {
health: null,
exposures: UNEVEN_EXPOSURES,
isExperimentDraft: false,
- hoursSinceStart: 72,
expected: null,
},
{
@@ -47,44 +61,32 @@ describe('healthPanelFindings', () => {
health: { findings: [serverFinding('no_metric')] },
exposures: null,
isExperimentDraft: false,
- hoursSinceStart: 72,
expected: ['no_metric'],
},
{
- name: 'no zero-exposure finding on a draft',
- health: { findings: [serverFinding('flag_live_before_launch')] },
- exposures: NO_EXPOSURES,
- isExperimentDraft: true,
- hoursSinceStart: null,
- expected: ['flag_live_before_launch'],
- },
- {
- name: 'no users exposed a day after launch',
- health: { findings: [] },
- exposures: NO_EXPOSURES,
+ name: 'the findings of the exposure answer join those of the experiment read',
+ health: { findings: [serverFinding('no_metric')] },
+ exposures: UNEVEN_EXPOSURES,
isExperimentDraft: false,
- hoursSinceStart: 24,
- expected: ['zero_exposures'],
+ expected: ['no_metric', 'srm', 'bias_risk_multiple_excluded'],
},
{
- name: 'no zero-exposure finding in the first day',
- health: { findings: [] },
- exposures: NO_EXPOSURES,
- isExperimentDraft: false,
- hoursSinceStart: 23,
- expected: [],
+ name: 'a draft shows no finding of the exposure answer that a reset left in the page',
+ health: { findings: [serverFinding('flag_live_before_launch')] },
+ exposures: UNEVEN_EXPOSURES,
+ isExperimentDraft: true,
+ expected: ['flag_live_before_launch'],
},
{
- name: 'a finding the server already sent is not added again from the exposures',
+ name: 'a code the experiment read sent is not added again from the exposure answer',
health: { findings: [serverFinding('bias_risk_multiple_excluded')] },
exposures: UNEVEN_EXPOSURES,
isExperimentDraft: false,
- hoursSinceStart: 72,
expected: ['bias_risk_multiple_excluded', 'srm'],
},
- ])('$name', ({ health, exposures, isExperimentDraft, hoursSinceStart, expected }) => {
- const input = { exposures, isExperimentDraft, hoursSinceStart } as ExposureHealthInput
-
- expect(healthPanelFindings(health, input)?.map(({ code }) => code) ?? null).toEqual(expected)
+ ])('$name', ({ health, exposures, isExperimentDraft, expected }) => {
+ expect(healthPanelFindings(health, exposures, isExperimentDraft)?.map(({ code }) => code) ?? null).toEqual(
+ expected
+ )
})
})
diff --git a/products/experiments/frontend/health/healthPanelFindings.ts b/products/experiments/frontend/health/healthPanelFindings.ts
index e7339adeaf54..a489eb18c86a 100644
--- a/products/experiments/frontend/health/healthPanelFindings.ts
+++ b/products/experiments/frontend/health/healthPanelFindings.ts
@@ -4,79 +4,17 @@ import type { ExperimentExposureQueryResponse } from '~/queries/schema/schema-ge
import type { ExperimentHealthApi, ExperimentHealthFindingApi } from '../generated/api.schemas'
import type { ExperimentHealthFindingActionKind, ExperimentHealthFindingCode } from './experimentHealthFindingEvents'
-import { SAMPLE_RATIO_MISMATCH_DESCRIPTION, getTotalExposures, hasSampleRatioMismatch } from './exposureHealth'
-/** A finding of the health panel: one from the server, or one the page reads from the exposure answer. */
+/** A finding of the health panel, from the experiment read or from the exposure answer. */
export type HealthPanelFinding = Pick<ExperimentHealthFindingApi, 'subcode' | 'severity' | 'title' | 'detail'> & {
code: ExperimentHealthFindingCode
actions: ExperimentHealthFindingActionKind[]
}
-export interface ExposureHealthInput {
- exposures: ExperimentExposureQueryResponse | null | undefined
- isExperimentDraft: boolean
- /** Null before launch. */
- hoursSinceStart: number | null
-}
-
-// A new experiment often has no exposure in its first hours, so the finding waits as long as the
-// experiments scout does.
-export const ZERO_EXPOSURES_GRACE_HOURS = 24
-
export function hoursSinceStart(startDate: string | null | undefined): number | null {
return startDate ? dayjs().diff(startDate, 'hour', true) : null
}
-// The server's health checks read no exposures, so the page derives these three from the exposure
-// answer. The bias text matches products/experiments/backend/health/checks/bias_risk.py.
-function exposureFindings({
- exposures,
- isExperimentDraft,
- hoursSinceStart,
-}: ExposureHealthInput): HealthPanelFinding[] {
- if (isExperimentDraft || !exposures) {
- return []
- }
- const findings: HealthPanelFinding[] = []
- // The exposure query returns a series for every configured variant, with zero counts when
- // nobody was exposed, so only the total tells an experiment without exposures apart.
- if (
- getTotalExposures(exposures) === 0 &&
- hoursSinceStart !== null &&
- hoursSinceStart >= ZERO_EXPOSURES_GRACE_HOURS
- ) {
- findings.push({
- code: 'zero_exposures',
- subcode: null,
- severity: 'warning',
- title: 'No users exposed',
- detail: 'No users have been exposed to this experiment, so it shows no results. Users are counted when the exposure event is sent for them. Check that your code evaluates the linked feature flag and that the exposure criteria match the events you send.',
- actions: ['edit_exposure_criteria'],
- })
- }
- if (hasSampleRatioMismatch(exposures)) {
- findings.push({
- code: 'srm',
- subcode: null,
- severity: 'warning',
- title: 'Users are not split across variants as configured',
- detail: SAMPLE_RATIO_MISMATCH_DESCRIPTION,
- actions: [],
- })
- }
- if (exposures.bias_risk) {
- findings.push({
- code: 'bias_risk_multiple_excluded',
- subcode: null,
- severity: 'warning',
- title: 'Setup likely introduced bias',
- detail: `${exposures.bias_risk.multiple_variant_percentage.toFixed(1)}% of users were exposed to multiple variants. With an uneven variant split and the Exclude handling, these users were dropped more often from the smaller variant, so its metrics can be biased. Use an even split and control exposure with the overall rollout, or switch the handling to First seen.`,
- actions: ['adjust_distribution', 'use_first_seen_variant'],
- })
- }
- return findings
-}
-
/**
* The findings of the health panel, or null when the server sent no health findings. Null means that
* the reader does not have the health findings flag, or that a local flag write dropped stale findings.
@@ -84,11 +22,14 @@ function exposureFindings({
*/
export function healthPanelFindings(
health: ExperimentHealthApi | null | undefined,
- exposureInput: ExposureHealthInput
+ exposures: ExperimentExposureQueryResponse | null | undefined,
+ isExperimentDraft: boolean
): HealthPanelFinding[] | null {
if (!health) {
return null
}
- const serverCodes = new Set<string>(health.findings.map((finding) => finding.code))
- return [...health.findings, ...exposureFindings(exposureInput).filter(({ code }) => !serverCodes.has(code))]
+ // A reset to draft keeps the previous exposure answer in the page, so a draft shows none of its findings.
+ const exposureFindings = isExperimentDraft ? [] : (exposures?.health_findings ?? [])
+ const experimentCodes = new Set<string>(health.findings.map((finding) => finding.code))
+ return [...health.findings, ...exposureFindings.filter(({ code }) => !experimentCodes.has(code))]
}
diff --git a/products/experiments/skills/diagnosing-experiment-health/references/empty-experiment.md b/products/experiments/skills/diagnosing-experiment-health/references/empty-experiment.md
index cc43cf89c691..5ce82c0f1dea 100644
--- a/products/experiments/skills/diagnosing-experiment-health/references/empty-experiment.md
+++ b/products/experiments/skills/diagnosing-experiment-health/references/empty-experiment.md
@@ -21,7 +21,8 @@ The reverse case, `$feature_flag_called` with variant responses and no `$experim
An event that fails one of them is not counted at all.
There is no "no variant" bucket.
-A launched experiment without a counted exposure shows a total of 0 and a flat chart. "No exposures yet" is the text for a draft, for a start date after today, and for an exposure query that failed.
+A launched experiment without a counted exposure shows a total of 0 and a flat chart, and its open Exposures panel says "No exposures yet".
+The panel says the same for a draft, for a start date after today, and for an exposure query that failed.
The queries this file refers to are in `diagnostic-snapshot.md`, with their rules.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 10dda079478b..68f7e40e78c1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -43245,6 +43245,8 @@ export namespace Schemas {
* * `flag_live_before_launch` - Flag Live Before Launch
* * `bias_risk_multiple_excluded` - Bias Risk Multiple Excluded
* * `no_metric` - No Metric
+ * * `srm` - Sample Ratio Mismatch
+ * * `zero_exposures` - Zero Exposures
*/
export type ExperimentHealthFindingCodeEnum = typeof ExperimentHealthFindingCodeEnum[keyof typeof ExperimentHealthFindingCodeEnum];
@@ -43256,6 +43258,8 @@ export namespace Schemas {
FlagLiveBeforeLaunch: 'flag_live_before_launch',
BiasRiskMultipleExcluded: 'bias_risk_multiple_excluded',
NoMetric: 'no_metric',
+ Srm: 'srm',
+ ZeroExposures: 'zero_exposures',
} as const;
/**
@@ -43278,6 +43282,7 @@ export namespace Schemas {
* * `use_first_seen_variant` - Use First Seen Variant
* * `add_primary_metric` - Add Primary Metric
* * `add_secondary_metric` - Add Secondary Metric
+ * * `edit_exposure_criteria` - Edit Exposure Criteria
*/
export type ExperimentHealthFindingActionKindEnum = typeof ExperimentHealthFindingActionKindEnum[keyof typeof ExperimentHealthFindingActionKindEnum];
@@ -43288,6 +43293,7 @@ export namespace Schemas {
UseFirstSeenVariant: 'use_first_seen_variant',
AddPrimaryMetric: 'add_primary_metric',
AddSecondaryMetric: 'add_secondary_metric',
+ EditExposureCriteria: 'edit_exposure_criteria',
} as const;
/**
@@ -43303,7 +43309,9 @@ export namespace Schemas {
* * `flag_live_after_end` - Flag Live After End
* * `flag_live_before_launch` - Flag Live Before Launch
* * `bias_risk_multiple_excluded` - Bias Risk Multiple Excluded
- * * `no_metric` - No Metric */
+ * * `no_metric` - No Metric
+ * * `srm` - Sample Ratio Mismatch
+ * * `zero_exposures` - Zero Exposures */
code: ExperimentHealthFindingCodeEnum;
/**
* The case within the code, when a code covers several, for example 'running_but_no_rollout' within 'flag_off_while_running'. Null when the code has one case.
@@ -43582,6 +43590,57 @@ export namespace Schemas {
multiple_variant_handling?: MultipleVariantHandling | null;
}
+ /**
+ * The values behind the finding, such as the p-value of the sample ratio test. The keys depend on the code.
+ */
+ export type ExperimentExposureHealthFindingEvidence = {[key: string]: string | number | null};
+
+ export type ExperimentExposureHealthFindingActionKind = typeof ExperimentExposureHealthFindingActionKind[keyof typeof ExperimentExposureHealthFindingActionKind];
+
+
+ export const ExperimentExposureHealthFindingActionKind = {
+ EditExposureCriteria: 'edit_exposure_criteria',
+ AdjustDistribution: 'adjust_distribution',
+ UseFirstSeenVariant: 'use_first_seen_variant',
+ } as const;
+
+ export type ExperimentExposureHealthFindingCode = typeof ExperimentExposureHealthFindingCode[keyof typeof ExperimentExposureHealthFindingCode];
+
+
+ export const ExperimentExposureHealthFindingCode = {
+ ZeroExposures: 'zero_exposures',
+ Srm: 'srm',
+ BiasRiskMultipleExcluded: 'bias_risk_multiple_excluded',
+ } as const;
+
+ export type ExperimentExposureHealthFindingSeverity = typeof ExperimentExposureHealthFindingSeverity[keyof typeof ExperimentExposureHealthFindingSeverity];
+
+
+ export const ExperimentExposureHealthFindingSeverity = {
+ Critical: 'critical',
+ Warning: 'warning',
+ Info: 'info',
+ } as const;
+
+ export interface ExperimentExposureHealthFinding {
+ /** The actions that fix the problem, in order of preference. */
+ actions: ExperimentExposureHealthFindingActionKind[];
+ /** Stable identifier of the problem. Each code has one meaning across every surface that reports it. */
+ code: ExperimentExposureHealthFindingCode;
+ /** What is wrong, what it does to the experiment, and how to fix it. */
+ detail: string;
+ /** The id of the matching diagnostic in the diagnosing-experiment-health skill, for example 'A2'. Null when the skill has none. */
+ diagnostic_ref: string | null;
+ /** The values behind the finding, such as the p-value of the sample ratio test. The keys depend on the code. */
+ evidence: ExperimentExposureHealthFindingEvidence;
+ /** How much the problem affects the results: critical, warning, or info. */
+ severity: ExperimentExposureHealthFindingSeverity;
+ /** The case within the code, when a code covers several. Null when the code has one case. */
+ subcode: string | null;
+ /** One-line summary of the problem. */
+ title: string;
+ }
+
export type ExperimentExposureQueryFeatureFlag = { [key: string]: unknown };
export interface FeatureFlagGroupType {
@@ -43628,6 +43687,8 @@ export namespace Schemas {
export interface ExperimentExposureQueryResponse {
bias_risk?: BiasRisk | null;
date_range: DateRange;
+ /** Health check diagnostics that read the exposures: zero exposures, a sample ratio mismatch, and bias. Empty when every check passed. */
+ health_findings?: ExperimentExposureHealthFinding[] | null;
kind?: 'ExperimentExposureQuery';
sample_ratio_mismatch?: SampleRatioMismatch | null;
timeseries: ExperimentExposureTimeSeries[];
@@ -89830,6 +89891,8 @@ export namespace Schemas {
export interface QueryResponseAlternative21 {
bias_risk?: BiasRisk | null;
date_range: DateRange;
+ /** Health check diagnostics that read the exposures: zero exposures, a sample ratio mismatch, and bias. Empty when every check passed. */
+ health_findings?: ExperimentExposureHealthFinding[] | null;
kind?: 'ExperimentExposureQuery';
sample_ratio_mismatch?: SampleRatioMismatch | null;
timeseries: ExperimentExposureTimeSeries[];