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): add the experiment health layer scaffolding (#112916)

Marcel Poelker4492dab2886f
diff --git a/products/experiments/backend/analysis_health.py b/products/experiments/backend/analysis_health.py
deleted file mode 100644
index 8f3f79a6d86a..000000000000
--- a/products/experiments/backend/analysis_health.py
+++ /dev/null
@@ -1,50 +0,0 @@
-"""
-Analysis-health signals for experiments. Pure functions — no I/O.
-
-Currently evaluates one signal: asymmetric `$multiple`-exclusion bias on uneven
-splits. Designed to grow (SRM, low exposures, variant drift, ...) as additional
-pure evaluators when needed.
-"""
-
-from posthog.schema import BiasRisk, MultipleVariantHandling
-
-from products.experiments.backend.variant_distribution import is_evenly_distributed
-
-MULTIPLE_VARIANT_KEY = "$multiple"
-
-# `$multiple` share above this triggers the warning. Below this, the asymmetric-
-# exclusion effect on arm means is too small to matter in practice.
-MULTIPLE_VARIANT_BIAS_THRESHOLD = 0.1 # on the 0-100 scale (0.1 = 0.1%)
-
-
-def evaluate_bias_risk(
- flag_variants: list[dict] | None,
- multiple_variant_handling: MultipleVariantHandling,
- total_exposures: dict[str, int],
-) -> BiasRisk | None:
- """
- Empirically observed multi-variant exclusion bias risk: uneven split + EXCLUDE
- handling + observed `$multiple` share above the threshold.
- Returns a `BiasRisk` only when all three conditions hold; `None` otherwise.
- """
- if multiple_variant_handling != MultipleVariantHandling.EXCLUDE:
- return None
-
- variants = flag_variants or []
- if not variants:
- return None
-
- rollout_percentages = [variant.get("rollout_percentage", 0) for variant in variants]
- if is_evenly_distributed(rollout_percentages):
- return None
-
- total_observed = sum(total_exposures.values())
- if total_observed <= 0:
- return None
-
- multiple_observed = total_exposures.get(MULTIPLE_VARIANT_KEY, 0)
- multiple_variant_percentage = (multiple_observed / total_observed) * 100
- if multiple_variant_percentage <= MULTIPLE_VARIANT_BIAS_THRESHOLD:
- return None
-
- return BiasRisk(multiple_variant_percentage=multiple_variant_percentage)
diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.py
index af9255e92bbd..b89aac79687b 100644
--- a/products/experiments/backend/facade/contracts.py
+++ b/products/experiments/backend/facade/contracts.py
@@ -5,11 +5,13 @@ These are framework-free frozen dataclasses that define the interface
between the experiments product and the rest of the system.
"""
+from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING, Any
from posthog.dataclasses import frozen
+from posthog.enums import LabeledStrEnum
if TYPE_CHECKING:
from posthog.schema import MaxExperimentSummaryContext
@@ -93,6 +95,40 @@ class ExperimentStatus:
return self.start_date is not None and self.end_date is None and not self.archived
+class ExperimentHealthFindingCode(LabeledStrEnum):
+ # pinned: the page sends these values as `finding_code` on the health finding events
+ # (products/experiments/frontend/health/experimentHealthFindingEvents.ts), and insights group on them.
+ BIAS_RISK_MULTIPLE_EXCLUDED = "bias_risk_multiple_excluded"
+
+
+class ExperimentHealthFindingSeverity(LabeledStrEnum):
+ # The values are the severities of the platform's health issues (posthog/models/health_issue.py), so a
+ # finding can become a health issue by value. The labels differ on purpose: two choice sets with the same
+ # values and labels share one OpenAPI enum, and the generated name of the other one would change.
+ CRITICAL = "critical", "Critical severity"
+ WARNING = "warning", "Warning severity"
+ INFO = "info", "Info severity"
+
+
+class ExperimentHealthFindingActionKind(LabeledStrEnum):
+ ADJUST_DISTRIBUTION = "adjust_distribution"
+ USE_FIRST_SEEN_VARIANT = "use_first_seen_variant"
+
+
+@frozen
+class ExperimentHealthFinding:
+ """One problem that a health check found in an experiment, with what fixes it."""
+
+ code: ExperimentHealthFindingCode
+ subcode: str | None
+ severity: ExperimentHealthFindingSeverity
+ title: str
+ detail: str
+ evidence: Mapping[str, str | int | float | None]
+ actions: tuple[ExperimentHealthFindingActionKind, ...]
+ diagnostic_ref: str | None
+
+
@dataclass(frozen=True)
class CreateExperimentInput:
"""
diff --git a/products/experiments/backend/health/__init__.py b/products/experiments/backend/health/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/experiments/backend/health/checks/__init__.py b/products/experiments/backend/health/checks/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/experiments/backend/health/checks/bias_risk.py b/products/experiments/backend/health/checks/bias_risk.py
new file mode 100644
index 000000000000..76809a40ede5
--- /dev/null
+++ b/products/experiments/backend/health/checks/bias_risk.py
@@ -0,0 +1,81 @@
+"""Multi-variant exclusion bias on an uneven split. Pure functions, no I/O."""
+
+from collections.abc import Mapping, Sequence
+
+from posthog.schema import BiasRisk, MultipleVariantHandling
+
+from products.experiments.backend.facade.contracts import (
+ ExperimentHealthFinding,
+ ExperimentHealthFindingActionKind,
+ ExperimentHealthFindingCode,
+ ExperimentHealthFindingSeverity,
+)
+from products.experiments.backend.health.context import HealthContext
+from products.experiments.backend.variant_distribution import is_evenly_distributed
+
+MULTIPLE_VARIANT_KEY = "$multiple"
+
+# `$multiple` share above this triggers the warning. Below this, the asymmetric-
+# exclusion effect on arm means is too small to matter in practice.
+MULTIPLE_VARIANT_BIAS_THRESHOLD = 0.1 # on the 0-100 scale (0.1 = 0.1%)
+
+
+def evaluate_bias_risk(
+ rollout_percentages: Sequence[float | None],
+ multiple_variant_handling: MultipleVariantHandling,
+ total_exposures: Mapping[str, int],
+) -> BiasRisk | None:
+ """
+ Empirically observed multi-variant exclusion bias risk: uneven split + EXCLUDE
+ handling + observed `$multiple` share above the threshold.
+ Returns a `BiasRisk` only when all three conditions hold; `None` otherwise.
+ """
+ if multiple_variant_handling != MultipleVariantHandling.EXCLUDE:
+ return None
+
+ if not rollout_percentages:
+ return None
+
+ if is_evenly_distributed(rollout_percentages):
+ return None
+
+ total_observed = sum(total_exposures.values())
+ if total_observed <= 0:
+ return None
+
+ multiple_observed = total_exposures.get(MULTIPLE_VARIANT_KEY, 0)
+ multiple_variant_percentage = (multiple_observed / total_observed) * 100
+ if multiple_variant_percentage <= MULTIPLE_VARIANT_BIAS_THRESHOLD:
+ return None
+
+ return BiasRisk(multiple_variant_percentage=multiple_variant_percentage)
+
+
+def bias_risk_multiple_excluded(ctx: HealthContext) -> ExperimentHealthFinding | None:
+ if ctx.exposures is None or ctx.flag is None or ctx.has_ended:
+ return None
+ risk = evaluate_bias_risk(
+ rollout_percentages=[variant.rollout_percentage for variant in ctx.flag.variants],
+ multiple_variant_handling=ctx.exposures.multiple_variant_handling,
+ total_exposures=ctx.exposures.total_exposures,
+ )
+ if risk is None:
+ return None
+ return ExperimentHealthFinding(
+ code=ExperimentHealthFindingCode.BIAS_RISK_MULTIPLE_EXCLUDED,
+ subcode=None,
+ severity=ExperimentHealthFindingSeverity.WARNING,
+ title="Setup likely introduced bias",
+ detail=(
+ f"{risk.multiple_variant_percentage:.1f}% 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": risk.multiple_variant_percentage},
+ actions=(
+ ExperimentHealthFindingActionKind.ADJUST_DISTRIBUTION,
+ ExperimentHealthFindingActionKind.USE_FIRST_SEEN_VARIANT,
+ ),
+ diagnostic_ref="A1",
+ )
diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.py
new file mode 100644
index 000000000000..5eb8bdc81056
--- /dev/null
+++ b/products/experiments/backend/health/context.py
@@ -0,0 +1,30 @@
+from collections.abc import Mapping
+
+from posthog.schema import MultipleVariantHandling
+
+from posthog.dataclasses import frozen
+
+
+@frozen
+class FlagVariant:
+ rollout_percentage: float | None
+
+
+@frozen
+class FlagState:
+ variants: tuple[FlagVariant, ...]
+
+
+@frozen
+class ExposureTotals:
+ total_exposures: Mapping[str, int]
+ multiple_variant_handling: MultipleVariantHandling
+
+
+@frozen
+class HealthContext:
+ """Every input of the health checks, loaded once, so that each check is a pure function of it."""
+
+ has_ended: bool
+ flag: FlagState | None
+ exposures: ExposureTotals | None
diff --git a/products/experiments/backend/health/registry.py b/products/experiments/backend/health/registry.py
new file mode 100644
index 000000000000..13d98c79dbf0
--- /dev/null
+++ b/products/experiments/backend/health/registry.py
@@ -0,0 +1,27 @@
+from collections.abc import Callable
+
+from posthog.exceptions_capture import capture_exception
+
+from products.experiments.backend.facade.contracts import ExperimentHealthFinding
+from products.experiments.backend.health.checks.bias_risk import bias_risk_multiple_excluded
+from products.experiments.backend.health.context import HealthContext
+
+HealthCheck = Callable[[HealthContext], ExperimentHealthFinding | None]
+
+HEALTH_CHECKS: tuple[HealthCheck, ...] = (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."""
+ findings: list[ExperimentHealthFinding] = []
+ for check in HEALTH_CHECKS:
+ try:
+ finding = check(ctx)
+ except Exception as error:
+ # The findings ride on responses such as the experiment detail, so one failing check
+ # must not fail the response or hide the findings of the other checks.
+ capture_exception(error)
+ continue
+ if finding is not None:
+ findings.append(finding)
+ return findings
diff --git a/products/experiments/backend/health/test/__init__.py b/products/experiments/backend/health/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/experiments/backend/test/test_analysis_health.py b/products/experiments/backend/health/test/test_bias_risk.py
similarity index 80%
rename from products/experiments/backend/test/test_analysis_health.py
rename to products/experiments/backend/health/test/test_bias_risk.py
index cd35d3a676ca..4b889c1aa904 100644
--- a/products/experiments/backend/test/test_analysis_health.py
+++ b/products/experiments/backend/health/test/test_bias_risk.py
@@ -4,12 +4,12 @@ from parameterized import parameterized
from posthog.schema import BiasRisk, MultipleVariantHandling
-from products.experiments.backend.analysis_health import MULTIPLE_VARIANT_BIAS_THRESHOLD, evaluate_bias_risk
+from products.experiments.backend.health.checks.bias_risk import MULTIPLE_VARIANT_BIAS_THRESHOLD, evaluate_bias_risk
-UNEVEN_2WAY = [{"rollout_percentage": 80}, {"rollout_percentage": 20}]
-EVEN_2WAY = [{"rollout_percentage": 50}, {"rollout_percentage": 50}]
+UNEVEN_2WAY = [80, 20]
+EVEN_2WAY = [50, 50]
# Auto-distribution for 3 variants — should be treated as even, not uneven.
-AUTO_EVEN_3WAY = [{"rollout_percentage": 34}, {"rollout_percentage": 33}, {"rollout_percentage": 33}]
+AUTO_EVEN_3WAY = [34, 33, 33]
class TestEvaluateBiasRisk(TestCase):
@@ -32,7 +32,7 @@ class TestEvaluateBiasRisk(TestCase):
def test_reordered_auto_even_is_uneven(self):
# 33/34/33 doesn't match the auto-distribution result (34/33/33) — counts as uneven,
# mirroring the frontend's positional `isEvenlyDistributed` check.
- reordered = [{"rollout_percentage": 33}, {"rollout_percentage": 34}, {"rollout_percentage": 33}]
+ reordered = [33, 34, 33]
result = evaluate_bias_risk(
reordered, MultipleVariantHandling.EXCLUDE, {"a": 330, "b": 340, "c": 330, "$multiple": 50}
)
@@ -76,16 +76,10 @@ class TestEvaluateBiasRisk(TestCase):
MultipleVariantHandling.EXCLUDE,
{"control": 800, "test": 200, "$multiple": 50},
),
- (
- "none_variants",
- None,
- MultipleVariantHandling.EXCLUDE,
- {"control": 800, "test": 200, "$multiple": 50},
- ),
]
)
- def test_returns_none_when_not_at_risk(self, _name, flag_variants, handling, exposures):
- result = evaluate_bias_risk(flag_variants, handling, exposures)
+ def test_returns_none_when_not_at_risk(self, _name, rollout_percentages, handling, exposures):
+ result = evaluate_bias_risk(rollout_percentages, handling, exposures)
self.assertIsNone(result)
def test_threshold_boundary_strictly_greater_than(self):
diff --git a/products/experiments/backend/health/test/test_registry.py b/products/experiments/backend/health/test/test_registry.py
new file mode 100644
index 000000000000..6f7a68ffd348
--- /dev/null
+++ b/products/experiments/backend/health/test/test_registry.py
@@ -0,0 +1,58 @@
+from dataclasses import replace
+from typing import Any
+
+from unittest import TestCase
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.schema import MultipleVariantHandling
+
+from products.experiments.backend.facade.contracts import ExperimentHealthFindingCode
+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
+
+RUNNING_UNEVEN_SPLIT = HealthContext(
+ has_ended=False,
+ flag=FlagState(variants=(FlagVariant(rollout_percentage=80), FlagVariant(rollout_percentage=20))),
+ exposures=ExposureTotals(
+ total_exposures={"control": 800, "test": 200, "$multiple": 20},
+ multiple_variant_handling=MultipleVariantHandling.EXCLUDE,
+ ),
+)
+
+
+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}),
+ ]
+ )
+ 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))]
+
+ self.assertNotIn(ExperimentHealthFindingCode.BIAS_RISK_MULTIPLE_EXCLUDED, codes)
+
+ 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)
+
+ self.assertEqual(
+ [finding.code for finding in findings], [ExperimentHealthFindingCode.BIAS_RISK_MULTIPLE_EXCLUDED]
+ )
+ capture.assert_called_once()
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 62bd8851df80..e82915a8e1cd 100644
--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
@@ -27,7 +27,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
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.analysis_health import evaluate_bias_risk
+from products.experiments.backend.health.checks.bias_risk import evaluate_bias_risk
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
@@ -263,12 +263,12 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
if self.window_end_date is not None:
return None
multivariate_data = (self.query.feature_flag.get("filters") or {}).get("multivariate") or {}
- flag_variants = multivariate_data.get("variants", [])
+ 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(
- flag_variants=flag_variants,
+ rollout_percentages=[variant.get("rollout_percentage", 0) for variant in flag_variants],
multiple_variant_handling=exposure_params.multiple_variant_handling,
total_exposures=total_exposures,
)
diff --git a/products/experiments/backend/variant_distribution.py b/products/experiments/backend/variant_distribution.py
index c800e406f0c8..b2fea3cf5d62 100644
--- a/products/experiments/backend/variant_distribution.py
+++ b/products/experiments/backend/variant_distribution.py
@@ -7,6 +7,8 @@ two implementations in sync; differences will produce subtle UI/backend disagree
about whether a split is "even".
"""
+from collections.abc import Sequence
+
def even_distribution(variant_count: int) -> list[int]:
"""
@@ -28,7 +30,7 @@ def even_distribution(variant_count: int) -> list[int]:
return percentages
-def is_evenly_distributed(rollout_percentages: list[int]) -> bool:
+def is_evenly_distributed(rollout_percentages: Sequence[float | None]) -> bool:
"""
Treat anything matching the auto-even distribution as even — including the
integer-rounded cases like 34/33/33, matching the frontend's
@@ -36,4 +38,4 @@ def is_evenly_distributed(rollout_percentages: list[int]) -> bool:
"""
if not rollout_percentages:
return True
- return rollout_percentages == even_distribution(len(rollout_percentages))
+ return list(rollout_percentages) == even_distribution(len(rollout_percentages))
diff --git a/products/experiments/skills/diagnosing-experiment-health/references/bias-and-skew.md b/products/experiments/skills/diagnosing-experiment-health/references/bias-and-skew.md
index cd5cbf357bbd..28fbed8ba3cd 100644
--- a/products/experiments/skills/diagnosing-experiment-health/references/bias-and-skew.md
+++ b/products/experiments/skills/diagnosing-experiment-health/references/bias-and-skew.md
@@ -74,7 +74,7 @@ This is the signal behind the in-app banner "Setup likely introduced bias".
The exclusion is still in the numbers: the banner's absence on an ended experiment clears nothing.
<!-- Source for maintainers (may rot): evaluate_bias_risk and MULTIPLE_VARIANT_BIAS_THRESHOLD in
-products/experiments/backend/analysis_health.py; the end-date rule in _evaluate_bias_risk,
+products/experiments/backend/health/checks/bias_risk.py; the end-date rule in _evaluate_bias_risk,
products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py. Verify before citing. -->
**The warning-vs-visible gap.** The banner fires above 0.1%.
diff --git a/tach.toml b/tach.toml
index f377f22287b4..d7a8eeb9851c 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1144,7 +1144,6 @@ from = [
[[interfaces]]
expose = [
- "backend\\.analysis_health.*",
"backend\\.experiment_saved_metric_service.*",
"backend\\.experiment_service.*",
"backend\\.hogql_queries.*",