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): return health check findings on the experiment API (#113190)

Marcel Poelkerc32be90fc1fa
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 78cff26c7fe2..5bd4dbb03773 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -633,6 +633,18 @@ SPECTACULAR_SETTINGS = {
"SlackSummaryCadenceEnum": ["daily", "weekly", "monthly"],
# signals' report-metric role; AutoresearchModel.Role also sits on a field named `role`.
"RoleEnum": ["primary", "supporting"],
+ # Keeps the name `CodeEnum` for the dataset conflict codes of ai_observability. A second field named
+ # `code` with fixed values (the experiment health finding codes) would otherwise rename it, and the
+ # frontend imports of `CodeEnumApi` would break.
+ "CodeEnum": [
+ "dataset_archived",
+ "dataset_name_conflict",
+ "dataset_item_archived",
+ "dataset_item_active",
+ "client_item_id_conflict",
+ "limit_reached",
+ "stale_version",
+ ],
# replay_vision alert destinations: the create body and the alert's listed destinations share this set.
"VisionAlertDestinationTypeEnum": ["slack", "webhook"],
# The API-only pin kind uses StrEnum; name its component without a Django Choices class.
diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.py
index 4b97d50783e5..1492d157b737 100644
--- a/products/experiments/backend/facade/api.py
+++ b/products/experiments/backend/facade/api.py
@@ -13,6 +13,8 @@ from posthog.models.team import Team
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.hogql_queries.exposure_query_logic import (
DEFAULT_EXPOSURE_EVENT,
get_exposure_event_and_property,
@@ -20,7 +22,7 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (
)
from products.experiments.backend.models.experiment import Experiment as ExperimentModel
-from .contracts import CreateExperimentInput, Experiment
+from .contracts import CreateExperimentInput, Experiment, ExperimentHealthFinding
def create_experiment(*, team: Team, user: User, input_dto: CreateExperimentInput) -> Experiment:
@@ -120,6 +122,17 @@ def count_running_experiments_on_feature_flag_called(organization_id: UUID) -> i
return count
+def get_experiment_health_findings(*, team_id: int, experiment_id: int) -> list[ExperimentHealthFinding]:
+ """The findings of the health checks that read only the experiment, its flag and its linked metrics."""
+ experiment = (
+ ExperimentModel.objects.filter(team_id=team_id)
+ .select_related("feature_flag")
+ .prefetch_related("experimenttosavedmetric_set")
+ .get(id=experiment_id)
+ )
+ return evaluate_health(load_health_context(experiment))
+
+
def _experiment_model_to_dto(experiment: ExperimentModel) -> Experiment:
"""Convert Django model to DTO."""
return Experiment(
diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.py
index 31cbd87ee790..0bcb674db24a 100644
--- a/products/experiments/backend/health/context.py
+++ b/products/experiments/backend/health/context.py
@@ -4,6 +4,9 @@ from posthog.schema import MultipleVariantHandling
from posthog.dataclasses import frozen
+from products.experiments.backend.metric_resolution import saved_metric_link_role, saved_metric_links
+from products.experiments.backend.models.experiment import Experiment
+
@frozen
class FlagVariant:
@@ -48,12 +51,7 @@ class HealthContext:
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
+def parse_flag_state(*, active: bool, deleted: bool, groups: object, variants: object) -> FlagState:
return FlagState(
active=active,
deleted=deleted,
@@ -88,3 +86,27 @@ def _percentage(value: object) -> float | None:
if isinstance(value, bool) or not isinstance(value, int | float):
return None
return float(value)
+
+
+def _load_flag_state(experiment: Experiment) -> FlagState | None:
+ # django-stubs types the id as int, but an unsaved instance can carry None.
+ feature_flag_id: int | None = experiment.feature_flag_id
+ if feature_flag_id is None:
+ return None
+ flag = experiment.feature_flag
+ return parse_flag_state(
+ active=bool(flag.active), deleted=bool(flag.deleted), groups=flag.conditions, variants=flag.variants
+ )
+
+
+def load_health_context(experiment: Experiment, exposures: ExposureTotals | None = None) -> HealthContext:
+ shared_metric_roles = [saved_metric_link_role(link) for link in saved_metric_links(experiment)]
+ return HealthContext(
+ is_launched=experiment.is_launched,
+ has_ended=experiment.is_stopped,
+ archived=experiment.archived,
+ flag=_load_flag_state(experiment),
+ primary_metric_count=len(experiment.metrics or []) + shared_metric_roles.count("primary"),
+ secondary_metric_count=len(experiment.metrics_secondary or []) + shared_metric_roles.count("secondary"),
+ exposures=exposures,
+ )
diff --git a/products/experiments/backend/health/test/test_flag_state.py b/products/experiments/backend/health/test/test_flag_state.py
index 6dde1f705913..267961793262 100644
--- a/products/experiments/backend/health/test/test_flag_state.py
+++ b/products/experiments/backend/health/test/test_flag_state.py
@@ -1,3 +1,5 @@
+from typing import Any
+
from unittest import TestCase
from parameterized import parameterized
@@ -43,12 +45,17 @@ DRAFT = {"is_launched": False, "has_ended": False}
def _context(
- status: dict[str, bool], *, active: bool, filters: object, deleted: bool = False, archived: bool = False
+ status: dict[str, bool], *, active: bool, filters: dict[str, Any], deleted: bool = False, archived: bool = False
) -> HealthContext:
return HealthContext(
**status,
archived=archived,
- flag=parse_flag_state(active=active, deleted=deleted, filters=filters),
+ flag=parse_flag_state(
+ active=active,
+ deleted=deleted,
+ groups=filters.get("groups"),
+ variants=(filters.get("multivariate") or {}).get("variants"),
+ ),
primary_metric_count=1,
secondary_metric_count=0,
exposures=None,
@@ -115,7 +122,6 @@ class TestFlagState(TestCase):
("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",
diff --git a/products/experiments/backend/metric_resolution.py b/products/experiments/backend/metric_resolution.py
index 50336aae0a2f..15780714038c 100644
--- a/products/experiments/backend/metric_resolution.py
+++ b/products/experiments/backend/metric_resolution.py
@@ -128,6 +128,12 @@ def saved_metric_links(experiment: Experiment) -> list[ExperimentToSavedMetric]:
return sorted(links, key=lambda link: link.id)
+def saved_metric_link_role(link: ExperimentToSavedMetric) -> MetricRole:
+ """The role of a shared-metric link. The API accepts a link without metadata, and such a link is primary."""
+ metadata = link.metadata if isinstance(link.metadata, dict) else {}
+ return "secondary" if metadata.get("type") == "secondary" else "primary"
+
+
def _resolve_saved_metrics(experiment: Experiment) -> list[ResolvedExperimentMetric]:
"""Saved/shared metrics linked to the experiment, with the link overrides applied. The link's
metadata["type"] holds the role, and a missing type means primary."""
@@ -140,7 +146,7 @@ def _resolve_saved_metrics(experiment: Experiment) -> list[ResolvedExperimentMet
resolved.append(
ResolvedExperimentMetric(
uuid=saved_query["uuid"],
- role="secondary" if metadata.get("type") == "secondary" else "primary",
+ role=saved_metric_link_role(link),
definition=resolve_saved_metric_definition(saved_query, metadata),
)
)
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index bf8ad5e03f19..2f0525db917f 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -6,8 +6,9 @@ All serializer classes and custom field classes live here.
ViewSet remains in experiments.py.
"""
+import logging
from copy import deepcopy
-from typing import Annotated, Any, TypeGuard
+from typing import Annotated, Any, Final, TypeGuard
from django.utils import timezone
@@ -39,11 +40,18 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import UserBasicSerializer
from posthog.api.tagged_item import BULK_UPDATE_TAGS_MAX_TAGS, TAG_NAME_MAX_LENGTH, TaggedItemSerializerMixin
from posthog.models.team.team import Team
+from posthog.permissions import posthog_feature_flag_enabled
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
from products.ai_observability.backend.models.llm_prompt import LLMPrompt
from products.experiments.backend.experiment_service import ExperimentService
-from products.experiments.backend.facade.contracts import CreateExperimentInput
+from products.experiments.backend.facade.api import get_experiment_health_findings
+from products.experiments.backend.facade.contracts import (
+ CreateExperimentInput,
+ ExperimentHealthFindingActionKind,
+ ExperimentHealthFindingCode,
+ ExperimentHealthFindingSeverity,
+)
from products.experiments.backend.facade.timeseries import METRIC_BUILDERS, resolve_saved_metric_definition
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.exposure_query_logic import resolve_default_exposure_event
@@ -84,6 +92,9 @@ from ee.clickhouse.views.experiment_holdouts import ExperimentHoldoutSerializer
from ee.clickhouse.views.experiment_saved_metrics import ExperimentToSavedMetricSerializer
tracer = trace.get_tracer(__name__)
+logger = logging.getLogger(__name__)
+
+EXPERIMENT_HEALTH_FINDINGS_FLAG: Final = "experiment-health-findings"
class _ExperimentApiMetricsList(PydanticRootModel):
@@ -179,6 +190,66 @@ class ExperimentMetricDefinitionField(serializers.JSONField):
pass
+@extend_schema_field(
+ {
+ "type": "object",
+ "additionalProperties": {"oneOf": [{"type": "string"}, {"type": "number"}], "nullable": True},
+ }
+)
+class ExperimentHealthEvidenceField(serializers.DictField):
+ pass
+
+
+class ExperimentHealthFindingSerializer(serializers.Serializer):
+ code = serializers.ChoiceField(
+ choices=ExperimentHealthFindingCode.choices,
+ help_text="Stable identifier of the problem. Each code has one meaning across every surface that reports it.",
+ )
+ subcode = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "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."
+ ),
+ )
+ severity = serializers.ChoiceField(
+ choices=ExperimentHealthFindingSeverity.choices,
+ help_text="How much the problem affects the results: critical, warning, or info.",
+ )
+ title = serializers.CharField(help_text="One-line summary of the problem.")
+ detail = serializers.CharField(help_text="What is wrong, what it does to the experiment, and how to fix it.")
+ evidence = ExperimentHealthEvidenceField(
+ help_text=(
+ "The values behind the finding, such as the key of a shipped variant or the share of users "
+ "exposed to multiple variants. The keys depend on the code."
+ ),
+ )
+ actions = serializers.ListField(
+ child=serializers.ChoiceField(choices=ExperimentHealthFindingActionKind.choices),
+ help_text=(
+ "The actions that fix the problem, in order of preference, for example 'open_feature_flag' "
+ "or 'add_primary_metric'."
+ ),
+ )
+ diagnostic_ref = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "The id of the matching diagnostic in the diagnosing-experiment-health skill, for example 'A5'. "
+ "Null when the skill has none."
+ ),
+ )
+
+
+class ExperimentHealthSerializer(serializers.Serializer):
+ findings = ExperimentHealthFindingSerializer(
+ many=True,
+ help_text=(
+ "Problems that the health checks found in the experiment's configuration and its feature flag. "
+ "Empty when every check passed."
+ ),
+ )
+
+
class ExperimentBaseSerializer(
TaggedItemSerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer
):
@@ -501,6 +572,13 @@ class ExperimentSerializer(ExperimentBaseSerializer):
"experiment would resolve to if launched now."
),
)
+ health = serializers.SerializerMethodField(
+ help_text=(
+ "Health check diagnostics for this experiment: problems in its configuration and its feature "
+ "flag that keep it from producing trustworthy results, each with a fix. Read `findings` first "
+ "when you diagnose an experiment. Null where health checks are not enabled yet."
+ ),
+ )
version = serializers.IntegerField(
required=False,
allow_null=True,
@@ -597,6 +675,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):
"is_legacy",
"can_freeze_exposure",
"resolved_exposure_event",
+ "health",
"user_access_level",
"tags",
]
@@ -612,6 +691,7 @@ class ExperimentSerializer(ExperimentBaseSerializer):
"status",
"can_freeze_exposure",
"resolved_exposure_event",
+ "health",
"user_access_level",
]
@@ -634,6 +714,34 @@ class ExperimentSerializer(ExperimentBaseSerializer):
# launched today, which is what the setup UI needs to show.
return resolve_default_exposure_event(obj.team, obj.start_date or timezone.now())
+ @extend_schema_field(ExperimentHealthSerializer(allow_null=True))
+ def get_health(self, obj: Experiment) -> dict[str, Any] | None:
+ if not self._health_findings_enabled(obj.team):
+ return None
+ return ExperimentHealthSerializer(
+ {"findings": get_experiment_health_findings(team_id=obj.team_id, experiment_id=obj.id)}
+ ).data
+
+ def _health_findings_enabled(self, team: Team) -> bool:
+ request = self.context.get("request")
+ user = getattr(request, "user", None)
+ distinct_id = getattr(user, "distinct_id", None)
+ email = getattr(user, "email", None)
+ try:
+ # Local evaluation keeps a network call off every experiment read. A flag that targets
+ # by email still matches, because the email goes in as a person property.
+ return posthog_feature_flag_enabled(
+ EXPERIMENT_HEALTH_FINDINGS_FLAG,
+ str(distinct_id or team.uuid),
+ organization_id=team.organization_id,
+ team_id=team.id,
+ person_properties={"email": email} if email else None,
+ only_evaluate_locally=True,
+ )
+ except Exception:
+ logger.warning("Failed to evaluate the experiment health findings flag", exc_info=True)
+ return False
+
@staticmethod
def _stored_saved_metric_queries(instance: Experiment) -> dict[int, dict[str, Any]]:
links = instance.experimenttosavedmetric_set.all()
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 5023a611d55a..6ca31da95711 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -60,7 +60,7 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.models.web_experiment import WebExperiment
-from products.experiments.backend.presentation.serializers import ExperimentSerializer
+from products.experiments.backend.presentation.serializers import EXPERIMENT_HEALTH_FINDINGS_FLAG, ExperimentSerializer
from products.experiments.backend.presentation.views import LIST_DEFERRED_FIELDS, EnterpriseExperimentsViewSet
from products.experiments.backend.setup_context import EXPERIMENT_SETUP_CONTEXT_FLAG
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext
@@ -77,6 +77,14 @@ def _make(cls, **attrs):
return instance
+_HEALTH_PAUSED = ("flag_off_while_running", "running_but_flag_disabled")
+_HEALTH_METRIC = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": "health-inline-metric",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+}
+
_FLAG_CONFIG_KEYS = (
"feature_flag_variants",
"rollout_percentage",
@@ -674,6 +682,80 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["resolved_exposure_event"], expected_event)
+ @parameterized.expand(
+ [
+ ("flag_off", False, {}, None, None),
+ ("no_metric", True, {}, None, [_HEALTH_PAUSED, ("no_metric", None)]),
+ ("inline_primary_metric_counts", True, {"metrics": [_HEALTH_METRIC]}, None, [_HEALTH_PAUSED]),
+ ("inline_secondary_metric_counts", True, {"metrics_secondary": [_HEALTH_METRIC]}, None, [_HEALTH_PAUSED]),
+ ("shared_primary_metric_counts", True, {}, {"metadata": {"type": "primary"}}, [_HEALTH_PAUSED]),
+ ("shared_secondary_metric_counts", True, {}, {"metadata": {"type": "secondary"}}, [_HEALTH_PAUSED]),
+ ("shared_metric_without_type_counts", True, {}, {}, [_HEALTH_PAUSED]),
+ ]
+ )
+ def test_detail_reports_health_findings(
+ self,
+ _name: str,
+ flag_enabled: bool,
+ inline_metrics: dict[str, list[dict[str, Any]]],
+ shared_metric_link: dict[str, Any] | None,
+ expected: list[tuple[str, str | None]] | None,
+ ) -> None:
+ experiment = Experiment.objects.create(
+ team=self.team,
+ name="health-findings",
+ feature_flag=FeatureFlag.objects.create(
+ team=self.team,
+ key=f"health-findings-{_name}",
+ created_by=self.user,
+ active=False,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ ),
+ start_date=timezone.now() - timedelta(days=3),
+ metrics=inline_metrics.get("metrics", []),
+ metrics_secondary=inline_metrics.get("metrics_secondary", []),
+ )
+ if shared_metric_link is not None:
+ saved_metric = ExperimentSavedMetric.objects.create(
+ team=self.team,
+ name="Shared metric",
+ created_by=self.user,
+ query={
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "$pageview"},
+ },
+ )
+ link_response = self.client.patch(
+ f"/api/projects/{self.team.id}/experiments/{experiment.id}",
+ {"saved_metrics_ids": [{"id": saved_metric.id, **shared_metric_link}]},
+ format="json",
+ )
+ self.assertEqual(link_response.status_code, status.HTTP_200_OK, link_response.json())
+
+ def fake_feature_enabled(flag_key: str, *args: Any, **kwargs: Any) -> bool:
+ return flag_enabled and flag_key == EXPERIMENT_HEALTH_FINDINGS_FLAG
+
+ with patch("posthoganalytics.feature_enabled", side_effect=fake_feature_enabled):
+ response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment.id}")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ health = response.json()["health"]
+ if expected is None:
+ self.assertIsNone(health)
+ return
+ self.assertEqual([(finding["code"], finding["subcode"]) for finding in health["findings"]], expected)
+ self.assertEqual(health["findings"][0]["actions"], ["open_feature_flag"])
+ self.assertEqual(health["findings"][0]["diagnostic_ref"], "A5")
+
@parameterized.expand(
[("after_cutoff", 30, "$experiment_exposure"), ("before_cutoff", -30, "$feature_flag_called")]
)
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index a92e51201298..9ead74ba521f 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2205,6 +2205,104 @@ export interface ExperimentApiMetricApi {
*/
export type _ExperimentApiMetricsListApi = ExperimentApiMetricApi[]
+/**
+ * * `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
+ */
+export type ExperimentHealthFindingCodeEnumApi =
+ (typeof ExperimentHealthFindingCodeEnumApi)[keyof typeof ExperimentHealthFindingCodeEnumApi]
+
+export const ExperimentHealthFindingCodeEnumApi = {
+ FlagOffWhileRunning: 'flag_off_while_running',
+ VariantShippedWhileRunning: 'variant_shipped_while_running',
+ FlagLiveAfterEnd: 'flag_live_after_end',
+ FlagLiveBeforeLaunch: 'flag_live_before_launch',
+ BiasRiskMultipleExcluded: 'bias_risk_multiple_excluded',
+ NoMetric: 'no_metric',
+} as const
+
+/**
+ * * `critical` - Critical severity
+ * * `warning` - Warning severity
+ * * `info` - Info severity
+ */
+export type ExperimentHealthFindingSeverityEnumApi =
+ (typeof ExperimentHealthFindingSeverityEnumApi)[keyof typeof ExperimentHealthFindingSeverityEnumApi]
+
+export const ExperimentHealthFindingSeverityEnumApi = {
+ Critical: 'critical',
+ Warning: 'warning',
+ Info: 'info',
+} as const
+
+/**
+ * * `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
+ */
+export type ExperimentHealthFindingActionKindEnumApi =
+ (typeof ExperimentHealthFindingActionKindEnumApi)[keyof typeof ExperimentHealthFindingActionKindEnumApi]
+
+export const ExperimentHealthFindingActionKindEnumApi = {
+ OpenFeatureFlag: 'open_feature_flag',
+ AdjustDistribution: 'adjust_distribution',
+ UseFirstSeenVariant: 'use_first_seen_variant',
+ AddPrimaryMetric: 'add_primary_metric',
+ AddSecondaryMetric: 'add_secondary_metric',
+} as const
+
+/**
+ * The values behind the finding, such as the key of a shipped variant or the share of users exposed to multiple variants. The keys depend on the code.
+ */
+export type ExperimentHealthFindingApiEvidence = { [key: string]: string | number | null }
+
+export interface ExperimentHealthFindingApi {
+ /** Stable identifier of the problem. Each code has one meaning across every surface that reports it.
+ *
+ * * `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 */
+ 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.
+ * @nullable
+ */
+ subcode: string | null
+ /** How much the problem affects the results: critical, warning, or info.
+ *
+ * * `critical` - Critical severity
+ * * `warning` - Warning severity
+ * * `info` - Info severity */
+ severity: ExperimentHealthFindingSeverityEnumApi
+ /** 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 key of a shipped variant or the share of users exposed to multiple variants. The keys depend on the code. */
+ evidence: ExperimentHealthFindingApiEvidence
+ /** The actions that fix the problem, in order of preference, for example 'open_feature_flag' or 'add_primary_metric'. */
+ actions: ExperimentHealthFindingActionKindEnumApi[]
+ /**
+ * The id of the matching diagnostic in the diagnosing-experiment-health skill, for example 'A5'. Null when the skill has none.
+ * @nullable
+ */
+ diagnostic_ref: string | null
+}
+
+export interface ExperimentHealthApi {
+ /** Problems that the health checks found in the experiment's configuration and its feature flag. Empty when every check passed. */
+ findings: ExperimentHealthFindingApi[]
+}
+
/**
* Experiment write payload. Identical to Experiment, plus the writable `feature_flag` config input.
*/
@@ -2333,6 +2431,8 @@ export interface ExperimentWriteApi {
readonly can_freeze_exposure: boolean
/** The event exposures are actually counted on when the experiment doesn't configure a custom one — `$feature_flag_called`, or `$experiment_exposure` once the team is in the rollout and the experiment started at or after the cutoff. Resolved server-side so clients display the same event the results queries read. For a draft, this is what the experiment would resolve to if launched now. */
readonly resolved_exposure_event: string
+ /** Health check diagnostics for this experiment: problems in its configuration and its feature flag that keep it from producing trustworthy results, each with a fix. Read `findings` first when you diagnose an experiment. Null where health checks are not enabled yet. */
+ readonly health: ExperimentHealthApi | null
/**
* The effective access level the user has for this object
* @nullable
@@ -2484,6 +2584,8 @@ export interface ExperimentApi {
readonly can_freeze_exposure: boolean
/** The event exposures are actually counted on when the experiment doesn't configure a custom one — `$feature_flag_called`, or `$experiment_exposure` once the team is in the rollout and the experiment started at or after the cutoff. Resolved server-side so clients display the same event the results queries read. For a draft, this is what the experiment would resolve to if launched now. */
readonly resolved_exposure_event: string
+ /** Health check diagnostics for this experiment: problems in its configuration and its feature flag that keep it from producing trustworthy results, each with a fix. Read `findings` first when you diagnose an experiment. Null where health checks are not enabled yet. */
+ readonly health: ExperimentHealthApi | null
/**
* The effective access level the user has for this object
* @nullable
@@ -2631,6 +2733,8 @@ export interface PatchedExperimentWriteApi {
readonly can_freeze_exposure?: boolean
/** The event exposures are actually counted on when the experiment doesn't configure a custom one — `$feature_flag_called`, or `$experiment_exposure` once the team is in the rollout and the experiment started at or after the cutoff. Resolved server-side so clients display the same event the results queries read. For a draft, this is what the experiment would resolve to if launched now. */
readonly resolved_exposure_event?: string
+ /** Health check diagnostics for this experiment: problems in its configuration and its feature flag that keep it from producing trustworthy results, each with a fix. Read `findings` first when you diagnose an experiment. Null where health checks are not enabled yet. */
+ readonly health?: ExperimentHealthApi | null
/**
* The effective access level the user has for this object
* @nullable
diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yaml
index f8959d5a0abd..4b9651333135 100644
--- a/products/experiments/mcp/tools.yaml
+++ b/products/experiments/mcp/tools.yaml
@@ -71,6 +71,9 @@ tools:
- experimentId
- experiment_id
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-calculate-running-time:
operation: experiments_calculate_running_time_create
enabled: true
@@ -407,6 +410,9 @@ tools:
aliases:
- experimentId
- experiment_id
+ response:
+ exclude:
+ - health
experiment-end:
operation: experiments_end_create
enabled: true
@@ -463,6 +469,9 @@ tools:
or the team's only connected repository. When several repositories are connected and no default is
set, the cleanup is skipped unless this is provided.
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-freeze-exposure:
operation: experiments_freeze_exposure_create
enabled: true
@@ -517,6 +526,9 @@ tools:
- experimentId
- experiment_id
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-get:
operation: experiments_retrieve
enabled: true
@@ -553,6 +565,7 @@ tools:
response:
exclude:
- saved_metrics.*.effective_query
+ - health
experiment-holdouts-create:
operation: experiment_holdouts_create
enabled: true
@@ -966,6 +979,9 @@ tools:
- experimentId
- experiment_id
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-pause:
operation: experiments_pause_create
enabled: true
@@ -1000,6 +1016,9 @@ tools:
- experimentId
- experiment_id
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-prompt-templates:
operation: experiments_prompt_templates_retrieve
enabled: true
@@ -1049,6 +1068,9 @@ tools:
- experimentId
- experiment_id
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-resume:
operation: experiments_resume_create
enabled: true
@@ -1082,6 +1104,9 @@ tools:
- experimentId
- experiment_id
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-saved-metrics-create:
operation: experiment_saved_metrics_create
enabled: true
@@ -1311,6 +1336,9 @@ tools:
or the team's only connected repository. When several repositories are connected and no default is
set, the cleanup is skipped unless this is provided.
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-stats:
operation: experiments_stats_retrieve
enabled: true
@@ -1398,6 +1426,9 @@ tools:
- experimentId
- experiment_id
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-unfreeze-exposure:
operation: experiments_unfreeze_exposure_create
enabled: true
@@ -1440,6 +1471,9 @@ tools:
- experimentId
- experiment_id
ui_app: experiment
+ response:
+ exclude:
+ - health
experiment-update:
operation: experiments_partial_update
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f8949a0eaa39..639a500255b7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -43060,6 +43060,104 @@ export namespace Schemas {
Stopped: 'stopped',
} as const;
+ /**
+ * * `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
+ */
+ export type ExperimentHealthFindingCodeEnum = typeof ExperimentHealthFindingCodeEnum[keyof typeof ExperimentHealthFindingCodeEnum];
+
+
+ export const ExperimentHealthFindingCodeEnum = {
+ FlagOffWhileRunning: 'flag_off_while_running',
+ VariantShippedWhileRunning: 'variant_shipped_while_running',
+ FlagLiveAfterEnd: 'flag_live_after_end',
+ FlagLiveBeforeLaunch: 'flag_live_before_launch',
+ BiasRiskMultipleExcluded: 'bias_risk_multiple_excluded',
+ NoMetric: 'no_metric',
+ } as const;
+
+ /**
+ * * `critical` - Critical severity
+ * * `warning` - Warning severity
+ * * `info` - Info severity
+ */
+ export type ExperimentHealthFindingSeverityEnum = typeof ExperimentHealthFindingSeverityEnum[keyof typeof ExperimentHealthFindingSeverityEnum];
+
+
+ export const ExperimentHealthFindingSeverityEnum = {
+ Critical: 'critical',
+ Warning: 'warning',
+ Info: 'info',
+ } as const;
+
+ /**
+ * * `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
+ */
+ export type ExperimentHealthFindingActionKindEnum = typeof ExperimentHealthFindingActionKindEnum[keyof typeof ExperimentHealthFindingActionKindEnum];
+
+
+ export const ExperimentHealthFindingActionKindEnum = {
+ OpenFeatureFlag: 'open_feature_flag',
+ AdjustDistribution: 'adjust_distribution',
+ UseFirstSeenVariant: 'use_first_seen_variant',
+ AddPrimaryMetric: 'add_primary_metric',
+ AddSecondaryMetric: 'add_secondary_metric',
+ } as const;
+
+ /**
+ * The values behind the finding, such as the key of a shipped variant or the share of users exposed to multiple variants. The keys depend on the code.
+ */
+ export type ExperimentHealthFindingEvidence = {[key: string]: string | number | null};
+
+ export interface ExperimentHealthFinding {
+ /** Stable identifier of the problem. Each code has one meaning across every surface that reports it.
+ *
+ * * `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 */
+ 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.
+ * @nullable
+ */
+ subcode: string | null;
+ /** How much the problem affects the results: critical, warning, or info.
+ *
+ * * `critical` - Critical severity
+ * * `warning` - Warning severity
+ * * `info` - Info severity */
+ severity: ExperimentHealthFindingSeverityEnum;
+ /** 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 key of a shipped variant or the share of users exposed to multiple variants. The keys depend on the code. */
+ evidence: ExperimentHealthFindingEvidence;
+ /** The actions that fix the problem, in order of preference, for example 'open_feature_flag' or 'add_primary_metric'. */
+ actions: ExperimentHealthFindingActionKindEnum[];
+ /**
+ * The id of the matching diagnostic in the diagnosing-experiment-health skill, for example 'A5'. Null when the skill has none.
+ * @nullable
+ */
+ diagnostic_ref: string | null;
+ }
+
+ export interface ExperimentHealth {
+ /** Problems that the health checks found in the experiment's configuration and its feature flag. Empty when every check passed. */
+ findings: ExperimentHealthFinding[];
+ }
+
/**
* Full experiment representation for the detail, create, and update endpoints.
*
@@ -43192,6 +43290,8 @@ export namespace Schemas {
readonly can_freeze_exposure: boolean;
/** The event exposures are actually counted on when the experiment doesn't configure a custom one — `$feature_flag_called`, or `$experiment_exposure` once the team is in the rollout and the experiment started at or after the cutoff. Resolved server-side so clients display the same event the results queries read. For a draft, this is what the experiment would resolve to if launched now. */
readonly resolved_exposure_event: string;
+ /** Health check diagnostics for this experiment: problems in its configuration and its feature flag that keep it from producing trustworthy results, each with a fix. Read `findings` first when you diagnose an experiment. Null where health checks are not enabled yet. */
+ readonly health: ExperimentHealth | null;
/**
* The effective access level the user has for this object
* @nullable
@@ -45603,6 +45703,8 @@ export namespace Schemas {
readonly can_freeze_exposure: boolean;
/** The event exposures are actually counted on when the experiment doesn't configure a custom one — `$feature_flag_called`, or `$experiment_exposure` once the team is in the rollout and the experiment started at or after the cutoff. Resolved server-side so clients display the same event the results queries read. For a draft, this is what the experiment would resolve to if launched now. */
readonly resolved_exposure_event: string;
+ /** Health check diagnostics for this experiment: problems in its configuration and its feature flag that keep it from producing trustworthy results, each with a fix. Read `findings` first when you diagnose an experiment. Null where health checks are not enabled yet. */
+ readonly health: ExperimentHealth | null;
/**
* The effective access level the user has for this object
* @nullable
@@ -78128,6 +78230,8 @@ export namespace Schemas {
readonly can_freeze_exposure?: boolean;
/** The event exposures are actually counted on when the experiment doesn't configure a custom one — `$feature_flag_called`, or `$experiment_exposure` once the team is in the rollout and the experiment started at or after the cutoff. Resolved server-side so clients display the same event the results queries read. For a draft, this is what the experiment would resolve to if launched now. */
readonly resolved_exposure_event?: string;
+ /** Health check diagnostics for this experiment: problems in its configuration and its feature flag that keep it from producing trustworthy results, each with a fix. Read `findings` first when you diagnose an experiment. Null where health checks are not enabled yet. */
+ readonly health?: ExperimentHealth | null;
/**
* The effective access level the user has for this object
* @nullable
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index a410acd65414..c5ccbf8ddb5f 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -76,7 +76,8 @@ const experimentArchive = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/archive/`,
body,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -453,7 +454,8 @@ const experimentDuplicate = (): ToolBase<ReturnType<typeof ExperimentDuplicateSc
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/duplicate/`,
body,
})
- return result
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return filtered
},
})
@@ -500,7 +502,8 @@ const experimentEnd = (): ToolBase<ReturnType<typeof ExperimentEndSchema>, WithP
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/end/`,
body,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -527,7 +530,8 @@ const experimentFreezeExposure = (): ToolBase<
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/freeze_exposure/`,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -551,7 +555,7 @@ const experimentGet = (): ToolBase<ReturnType<typeof ExperimentGetSchema>, WithP
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/`,
})
- const filtered = omitResponseFields(result, ['saved_metrics.*.effective_query']) as typeof result
+ const filtered = omitResponseFields(result, ['saved_metrics.*.effective_query', 'health']) as typeof result
return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -959,7 +963,8 @@ const experimentMigrate = (): ToolBase<
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/migrate/`,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -983,7 +988,8 @@ const experimentPause = (): ToolBase<ReturnType<typeof ExperimentPauseSchema>, W
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/pause/`,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -1022,7 +1028,8 @@ const experimentReset = (): ToolBase<ReturnType<typeof ExperimentResetSchema>, W
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/reset/`,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -1046,7 +1053,8 @@ const experimentResume = (): ToolBase<ReturnType<typeof ExperimentResumeSchema>,
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/resume/`,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -1311,7 +1319,8 @@ const experimentShipVariant = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/ship_variant/`,
body,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -1394,7 +1403,8 @@ const experimentUnarchive = (): ToolBase<
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/unarchive/`,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})
@@ -1421,7 +1431,8 @@ const experimentUnfreezeExposure = (): ToolBase<
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/experiments/${encodeURIComponent(String(params.id))}/unfreeze_exposure/`,
})
- return await withPostHogUrl(context, result, `/experiments/${result.id}`)
+ const filtered = omitResponseFields(result, ['health']) as typeof result
+ return await withPostHogUrl(context, filtered, `/experiments/${filtered.id}`)
},
})