:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): port the flag-state and no-metric health checks to the backend (#113150)
Marcel Poelkerc7f39be9fa3d
diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.pyindex b89aac79687b..b04f7c39cc65 100644--- a/products/experiments/backend/facade/contracts.py+++ b/products/experiments/backend/facade/contracts.py@@ -98,7 +98,12 @@ class ExperimentStatus: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.+ FLAG_OFF_WHILE_RUNNING = "flag_off_while_running"+ VARIANT_SHIPPED_WHILE_RUNNING = "variant_shipped_while_running"+ 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"class ExperimentHealthFindingSeverity(LabeledStrEnum):@@ -111,8 +116,11 @@ class ExperimentHealthFindingSeverity(LabeledStrEnum):class ExperimentHealthFindingActionKind(LabeledStrEnum):+ OPEN_FEATURE_FLAG = "open_feature_flag"ADJUST_DISTRIBUTION = "adjust_distribution"USE_FIRST_SEEN_VARIANT = "use_first_seen_variant"+ ADD_PRIMARY_METRIC = "add_primary_metric"+ ADD_SECONDARY_METRIC = "add_secondary_metric"@frozendiff --git a/products/experiments/backend/health/checks/flag_state.py b/products/experiments/backend/health/checks/flag_state.pynew file mode 100644index 000000000000..d5b23087e126--- /dev/null+++ b/products/experiments/backend/health/checks/flag_state.py@@ -0,0 +1,143 @@+"""+Conflicting states of an experiment and its feature flag. Pure functions, no I/O.++A port of the page's `experimentWarning` selector (frontend/src/scenes/experiments/experimentLogic.tsx)+and the flag helpers it calls (`hasZeroRollout`, `hasMultipleVariantsActive`, `isSingleVariantShipped`).+Change both sides together until the page reads these findings.+"""++from products.experiments.backend.facade.contracts import (+ ExperimentHealthFinding,+ ExperimentHealthFindingActionKind,+ ExperimentHealthFindingCode,+ ExperimentHealthFindingSeverity,+)+from products.experiments.backend.health.context import FlagState, HealthContext++# pinned: the page's warning keys. The page sends them as `finding_variant` and+# `warning_key` on its events, and picks the banner text by them.+RUNNING_BUT_FLAG_DISABLED = "running_but_flag_disabled"+RUNNING_BUT_NO_ROLLOUT = "running_but_no_rollout"+RUNNING_BUT_SINGLE_VARIANT_SHIPPED = "running_but_single_variant_shipped"+ENDED_BUT_MULTIPLE_VARIANTS_ROLLED_OUT = "ended_but_multiple_variants_rolled_out"+NOT_STARTED_BUT_MULTIPLE_VARIANTS_ROLLED_OUT = "not_started_but_multiple_variants_rolled_out"++_NOT_RUNNING_BUT_EXPOSED_TITLE = "The experiment is not running, but users are exposed to multiple variants"+++def flag_state(ctx: HealthContext) -> ExperimentHealthFinding | None:+ flag = ctx.flag+ # A deleted flag distributes no traffic, so flag-state findings don't apply.+ if flag is None or flag.deleted:+ return None++ zero_rollout = _has_zero_rollout(flag)+ single_variant_shipped = _is_single_variant_shipped(flag)++ if ctx.is_running:+ if not flag.active:+ return _finding(+ code=ExperimentHealthFindingCode.FLAG_OFF_WHILE_RUNNING,+ subcode=RUNNING_BUT_FLAG_DISABLED,+ title="The experiment is paused",+ detail=(+ "The linked feature flag is disabled while the experiment has not been ended. "+ "Resume or end the experiment."+ ),+ )+ if zero_rollout:+ return _finding(+ code=ExperimentHealthFindingCode.FLAG_OFF_WHILE_RUNNING,+ subcode=RUNNING_BUT_NO_ROLLOUT,+ title="The experiment is running, but no new users are being exposed",+ detail=(+ "The linked feature flag has a 0% rollout, so no new users are being exposed. "+ "Users exposed earlier are still included in the results. End the experiment with a "+ "conclusion, or increase the rollout percentage to expose users."+ ),+ )+ if single_variant_shipped:+ variant_key = _shipped_variant_key(flag)+ shipped = f'Variant "{variant_key}" is' if variant_key else "One variant is"+ return _finding(+ code=ExperimentHealthFindingCode.VARIANT_SHIPPED_WHILE_RUNNING,+ subcode=RUNNING_BUT_SINGLE_VARIANT_SHIPPED,+ title="The experiment is running, but all users see a single variant",+ detail=(+ f"{shipped} rolled out to 100% of users. The experiment is not comparing variants. "+ "End the experiment with a conclusion, or adjust the variant distribution of the linked "+ "feature flag to resume proper A/B testing."+ ),+ evidence={"variant_key": variant_key},+ )+ elif ctx.has_ended:+ if flag.active and _has_multiple_variants_active(flag) and not zero_rollout and not single_variant_shipped:+ return _finding(+ code=ExperimentHealthFindingCode.FLAG_LIVE_AFTER_END,+ subcode=ENDED_BUT_MULTIPLE_VARIANTS_ROLLED_OUT,+ title=_NOT_RUNNING_BUT_EXPOSED_TITLE,+ detail=(+ "This experiment has ended, but the linked feature flag is still active and distributing "+ "traffic across multiple variants. Disable the flag, or resume the experiment."+ ),+ )+ elif not ctx.archived:+ # The draft state is also reached again when resetting experiment measurements.+ if flag.active and _has_multiple_variants_active(flag) and not zero_rollout:+ return _finding(+ code=ExperimentHealthFindingCode.FLAG_LIVE_BEFORE_LAUNCH,+ subcode=NOT_STARTED_BUT_MULTIPLE_VARIANTS_ROLLED_OUT,+ title=_NOT_RUNNING_BUT_EXPOSED_TITLE,+ detail=(+ "This experiment hasn't launched yet, but the linked feature flag is already active and "+ "exposing users to multiple variants. Disable the flag, or start the experiment."+ ),+ )++ return None+++def _finding(+ *,+ code: ExperimentHealthFindingCode,+ subcode: str,+ title: str,+ detail: str,+ evidence: dict[str, str | int | float | None] | None = None,+) -> ExperimentHealthFinding:+ return ExperimentHealthFinding(+ code=code,+ subcode=subcode,+ severity=ExperimentHealthFindingSeverity.WARNING,+ title=title,+ detail=detail,+ evidence=evidence or {},+ actions=(ExperimentHealthFindingActionKind.OPEN_FEATURE_FLAG,),+ diagnostic_ref="A5",+ )+++def _has_zero_rollout(flag: FlagState) -> bool:+ # Only true when every release group is set to 0 explicitly. A group without a rollout+ # percentage serves everyone.+ return bool(flag.release_groups) and all(group.rollout_percentage == 0 for group in flag.release_groups)+++def _has_multiple_variants_active(flag: FlagState) -> bool:+ # A variant without a rollout percentage counts as active, as on the flag itself.+ return sum(1 for variant in flag.variants if variant.rollout_percentage != 0) > 1+++def _is_single_variant_shipped(flag: FlagState) -> bool:+ first_group = flag.release_groups[0] if flag.release_groups else None+ return (+ flag.active+ and first_group is not None+ and first_group.property_count == 0+ and first_group.rollout_percentage == 100+ and any(variant.rollout_percentage == 100 for variant in flag.variants)+ )+++def _shipped_variant_key(flag: FlagState) -> str | None:+ return next((variant.key for variant in flag.variants if variant.rollout_percentage == 100), None) or Nonediff --git a/products/experiments/backend/health/checks/no_metric.py b/products/experiments/backend/health/checks/no_metric.pynew file mode 100644index 000000000000..7f8f462353e8--- /dev/null+++ b/products/experiments/backend/health/checks/no_metric.py@@ -0,0 +1,29 @@+from products.experiments.backend.facade.contracts import (+ ExperimentHealthFinding,+ ExperimentHealthFindingActionKind,+ ExperimentHealthFindingCode,+ ExperimentHealthFindingSeverity,+)+from products.experiments.backend.health.context import HealthContext+++def no_metric(ctx: HealthContext) -> ExperimentHealthFinding | None:+ # The deprecated `filters` metric does not count, because no engine reads it.+ if not ctx.is_launched or ctx.primary_metric_count + ctx.secondary_metric_count > 0:+ return None+ return ExperimentHealthFinding(+ code=ExperimentHealthFindingCode.NO_METRIC,+ subcode=None,+ severity=ExperimentHealthFindingSeverity.WARNING,+ title="No metrics defined",+ detail=(+ "The experiment has launched, but it has no metric, so it shows no results. "+ "Add at least one metric. Metrics can be added, removed, or changed at any time."+ ),+ evidence={},+ actions=(+ ExperimentHealthFindingActionKind.ADD_PRIMARY_METRIC,+ ExperimentHealthFindingActionKind.ADD_SECONDARY_METRIC,+ ),+ diagnostic_ref=None,+ )diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.pyindex 5eb8bdc81056..31cbd87ee790 100644--- a/products/experiments/backend/health/context.py+++ b/products/experiments/backend/health/context.py@@ -7,11 +7,21 @@ from posthog.dataclasses import frozen@frozenclass FlagVariant:+ key: str | Nonerollout_percentage: float | None+@frozen+class FlagReleaseGroup:+ rollout_percentage: float | None+ property_count: int | None++@frozenclass FlagState:+ active: bool+ deleted: bool+ release_groups: tuple[FlagReleaseGroup, ...]variants: tuple[FlagVariant, ...]@@ -25,6 +35,56 @@ class ExposureTotals:class HealthContext:"""Every input of the health checks, loaded once, so that each check is a pure function of it."""+ is_launched: boolhas_ended: bool+ archived: boolflag: FlagState | None+ primary_metric_count: int+ secondary_metric_count: intexposures: ExposureTotals | None++ @property+ def is_running(self) -> bool:+ return self.is_launched and not self.has_ended+++def parse_flag_state(*, active: bool, deleted: bool, filters: object) -> FlagState:+ if not isinstance(filters, dict):+ filters = {}+ groups = filters.get("groups")+ multivariate = filters.get("multivariate")+ variants = multivariate.get("variants") if isinstance(multivariate, dict) else None+ return FlagState(+ active=active,+ deleted=deleted,+ release_groups=tuple(_release_group(group) for group in groups) if isinstance(groups, list) else (),+ variants=tuple(_variant(variant) for variant in variants) if isinstance(variants, list) else (),+ )+++def _release_group(group: object) -> FlagReleaseGroup:+ if not isinstance(group, dict):+ return FlagReleaseGroup(rollout_percentage=None, property_count=None)+ properties = group.get("properties")+ return FlagReleaseGroup(+ rollout_percentage=_percentage(group.get("rollout_percentage")),+ property_count=len(properties) if isinstance(properties, list) else None,+ )+++def _variant(variant: object) -> FlagVariant:+ if not isinstance(variant, dict):+ return FlagVariant(key=None, rollout_percentage=None)+ key = variant.get("key")+ return FlagVariant(+ key=key if isinstance(key, str) else None,+ rollout_percentage=_percentage(variant.get("rollout_percentage")),+ )+++def _percentage(value: object) -> float | None:+ # The page compares with `=== 0` and `=== 100`, so only a JSON number can match. A string or a+ # boolean must not, and Python's `False == 0` would let a boolean through.+ if isinstance(value, bool) or not isinstance(value, int | float):+ return None+ return float(value)diff --git a/products/experiments/backend/health/registry.py b/products/experiments/backend/health/registry.pyindex 13d98c79dbf0..6736f9eff150 100644--- a/products/experiments/backend/health/registry.py+++ b/products/experiments/backend/health/registry.py@@ -4,11 +4,13 @@ from posthog.exceptions_capture import capture_exceptionfrom products.experiments.backend.facade.contracts import ExperimentHealthFindingfrom 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_metricfrom products.experiments.backend.health.context import HealthContextHealthCheck = Callable[[HealthContext], ExperimentHealthFinding | None]-HEALTH_CHECKS: tuple[HealthCheck, ...] = (bias_risk_multiple_excluded,)+HEALTH_CHECKS: tuple[HealthCheck, ...] = (flag_state, no_metric, bias_risk_multiple_excluded)def evaluate(ctx: HealthContext) -> list[ExperimentHealthFinding]:diff --git a/products/experiments/backend/health/test/test_flag_state.py b/products/experiments/backend/health/test/test_flag_state.pynew file mode 100644index 000000000000..6dde1f705913--- /dev/null+++ b/products/experiments/backend/health/test/test_flag_state.py@@ -0,0 +1,147 @@+from unittest import TestCase++from parameterized import parameterized++from products.experiments.backend.facade.contracts import ExperimentHealthFindingCode+from products.experiments.backend.health.checks.flag_state import flag_state+from products.experiments.backend.health.context import HealthContext, parse_flag_state++# The flag documents and cases of the `experimentWarning` test in+# frontend/src/scenes/experiments/experimentLogic.test.ts, so that both sides answer alike.+MULTIVARIANT = {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [{"key": "control", "rollout_percentage": 50}, {"key": "test", "rollout_percentage": 50}]+ },+}+SHIPPED_VARIANT = {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [{"key": "control", "rollout_percentage": 0}, {"key": "test", "rollout_percentage": 100}]+ },+}+ZERO_ROLLOUT = {+ "groups": [{"properties": [], "rollout_percentage": 0}],+ "multivariate": {+ "variants": [{"key": "control", "rollout_percentage": 50}, {"key": "test", "rollout_percentage": 50}]+ },+}+ZERO_ROLLOUT_SHIPPED_VARIANT = {+ "groups": [{"properties": [], "rollout_percentage": 0}],+ "multivariate": {+ "variants": [{"key": "control", "rollout_percentage": 0}, {"key": "test", "rollout_percentage": 100}]+ },+}+SHIPPED_TO_SOME = {+ "groups": [{"properties": [{"key": "email", "value": "x", "type": "person"}], "rollout_percentage": 100}],+ "multivariate": SHIPPED_VARIANT["multivariate"],+}++RUNNING = {"is_launched": True, "has_ended": False}+ENDED = {"is_launched": True, "has_ended": True}+DRAFT = {"is_launched": False, "has_ended": False}+++def _context(+ status: dict[str, bool], *, active: bool, filters: object, deleted: bool = False, archived: bool = False+) -> HealthContext:+ return HealthContext(+ **status,+ archived=archived,+ flag=parse_flag_state(active=active, deleted=deleted, filters=filters),+ primary_metric_count=1,+ secondary_metric_count=0,+ exposures=None,+ )+++class TestFlagState(TestCase):+ @parameterized.expand(+ [+ ("running_normal_rollout", _context(RUNNING, active=True, filters=MULTIVARIANT), None),+ (+ "running_flag_disabled",+ _context(RUNNING, active=False, filters=MULTIVARIANT),+ (ExperimentHealthFindingCode.FLAG_OFF_WHILE_RUNNING, "running_but_flag_disabled", None),+ ),+ (+ "running_single_variant_shipped",+ _context(RUNNING, active=True, filters=SHIPPED_VARIANT),+ (+ ExperimentHealthFindingCode.VARIANT_SHIPPED_WHILE_RUNNING,+ "running_but_single_variant_shipped",+ "test",+ ),+ ),+ ("running_variant_shipped_to_some", _context(RUNNING, active=True, filters=SHIPPED_TO_SOME), None),+ (+ "running_zero_rollout",+ _context(RUNNING, active=True, filters=ZERO_ROLLOUT),+ (ExperimentHealthFindingCode.FLAG_OFF_WHILE_RUNNING, "running_but_no_rollout", None),+ ),+ (+ "running_zero_rollout_before_shipped_variant",+ _context(RUNNING, active=True, filters=ZERO_ROLLOUT_SHIPPED_VARIANT),+ (ExperimentHealthFindingCode.FLAG_OFF_WHILE_RUNNING, "running_but_no_rollout", None),+ ),+ (+ "ended_flag_distributing_variants",+ _context(ENDED, active=True, filters=MULTIVARIANT),+ (ExperimentHealthFindingCode.FLAG_LIVE_AFTER_END, "ended_but_multiple_variants_rolled_out", None),+ ),+ ("ended_zero_rollout", _context(ENDED, active=True, filters=ZERO_ROLLOUT), None),+ ("ended_flag_disabled", _context(ENDED, active=False, filters=MULTIVARIANT), None),+ ("ended_single_variant_shipped", _context(ENDED, active=True, filters=SHIPPED_VARIANT), None),+ (+ "archived_ended_flag_distributing_variants",+ _context(ENDED, active=True, filters=MULTIVARIANT, archived=True),+ (ExperimentHealthFindingCode.FLAG_LIVE_AFTER_END, "ended_but_multiple_variants_rolled_out", None),+ ),+ (+ "draft_flag_distributing_variants",+ _context(DRAFT, active=True, filters=MULTIVARIANT),+ (+ ExperimentHealthFindingCode.FLAG_LIVE_BEFORE_LAUNCH,+ "not_started_but_multiple_variants_rolled_out",+ None,+ ),+ ),+ (+ "archived_draft_flag_distributing_variants",+ _context(DRAFT, active=True, filters=MULTIVARIANT, archived=True),+ None,+ ),+ ("draft_zero_rollout", _context(DRAFT, active=True, filters=ZERO_ROLLOUT), None),+ ("draft_flag_disabled", _context(DRAFT, active=False, filters=MULTIVARIANT), None),+ ("ended_deleted_flag", _context(ENDED, active=True, filters=MULTIVARIANT, deleted=True), None),+ ("draft_deleted_flag", _context(DRAFT, active=True, filters=MULTIVARIANT, deleted=True), None),+ ("running_document_is_null", _context(RUNNING, active=True, filters=None), None),+ ("running_groups_are_null", _context(RUNNING, active=True, filters={**ZERO_ROLLOUT, "groups": None}), None),+ (+ "running_variants_are_null",+ _context(RUNNING, active=True, filters={**SHIPPED_VARIANT, "multivariate": {"variants": None}}),+ None,+ ),+ (+ "running_boolean_rollout_is_not_zero",+ _context(+ RUNNING,+ active=True,+ filters={**ZERO_ROLLOUT, "groups": [{"properties": [], "rollout_percentage": False}]},+ ),+ None,+ ),+ ]+ )+ def test_flag_state(+ self, _name: str, ctx: HealthContext, expected: tuple[ExperimentHealthFindingCode, str, str | None] | None+ ) -> None:+ finding = flag_state(ctx)++ if expected is None:+ self.assertIsNone(finding)+ return+ assert finding is not None+ code, subcode, variant_key = expected+ self.assertEqual((finding.code, finding.subcode), (code, subcode))+ self.assertEqual(finding.evidence.get("variant_key"), variant_key)diff --git a/products/experiments/backend/health/test/test_no_metric.py b/products/experiments/backend/health/test/test_no_metric.pynew file mode 100644index 000000000000..e58913946362--- /dev/null+++ b/products/experiments/backend/health/test/test_no_metric.py@@ -0,0 +1,38 @@+from typing import Any++from unittest import TestCase++from parameterized import parameterized++from products.experiments.backend.facade.contracts import ExperimentHealthFindingCode+from products.experiments.backend.health.checks.no_metric import no_metric+from products.experiments.backend.health.context import HealthContext+++def _context(**changes: Any) -> HealthContext:+ values: dict[str, Any] = {+ "is_launched": True,+ "has_ended": False,+ "archived": False,+ "flag": None,+ "primary_metric_count": 0,+ "secondary_metric_count": 0,+ "exposures": None,+ }+ return HealthContext(**{**values, **changes})+++class TestNoMetric(TestCase):+ @parameterized.expand(+ [+ ("running_without_metrics", _context(), True),+ ("ended_without_metrics", _context(has_ended=True), True),+ ("draft_without_metrics", _context(is_launched=False), False),+ ("secondary_metric_only", _context(secondary_metric_count=1), False),+ ("primary_metric_only", _context(primary_metric_count=1), False),+ ]+ )+ def test_no_metric(self, _name: str, ctx: HealthContext, expected: bool) -> None:+ finding = no_metric(ctx)++ self.assertEqual(finding.code if finding else None, ExperimentHealthFindingCode.NO_METRIC if expected else None)diff --git a/products/experiments/backend/health/test/test_registry.py b/products/experiments/backend/health/test/test_registry.pyindex 6f7a68ffd348..f69dbb1ca03d 100644--- a/products/experiments/backend/health/test/test_registry.py+++ b/products/experiments/backend/health/test/test_registry.py@@ -15,8 +15,20 @@ from products.experiments.backend.health.context import ExposureTotals, FlagStatfrom products.experiments.backend.health.registry import evaluateRUNNING_UNEVEN_SPLIT = HealthContext(+ is_launched=True,has_ended=False,- flag=FlagState(variants=(FlagVariant(rollout_percentage=80), FlagVariant(rollout_percentage=20))),+ archived=False,+ flag=FlagState(+ active=True,+ deleted=False,+ release_groups=(),+ variants=(+ FlagVariant(key="control", rollout_percentage=80),+ FlagVariant(key="test", rollout_percentage=20),+ ),+ ),+ primary_metric_count=1,+ secondary_metric_count=0,exposures=ExposureTotals(total_exposures={"control": 800, "test": 200, "$multiple": 20},multiple_variant_handling=MultipleVariantHandling.EXCLUDE,