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): serve the health engine's inputs to staff (#118396)

Marcel Poelker9bdf62ed493c
diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.py
index 91a6b234fa4e..49ec281a8959 100644
--- a/products/experiments/backend/facade/api.py
+++ b/products/experiments/backend/facade/api.py
@@ -5,7 +5,7 @@ This module provides the public interface for creating and managing experiments
using framework-free DTOs, wrapping the existing ExperimentService.
"""
-from dataclasses import replace
+from typing import Any
from uuid import UUID
from rest_framework.exceptions import ValidationError
@@ -14,9 +14,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.condition_set_traffic import load_condition_set_traffic
-from products.experiments.backend.health.context import load_health_context
-from products.experiments.backend.health.exposure_gate import load_split_history
+from products.experiments.backend.health.inputs_payload import health_inputs_payload
+from products.experiments.backend.health.loader import load_experiment_health_context, load_experiment_health_inputs
from products.experiments.backend.health.registry import (
EXPERIMENT_HEALTH_CHECKS,
evaluate as evaluate_health,
@@ -133,16 +132,20 @@ def get_experiment_health_findings(
) -> list[ExperimentHealthFinding]:
"""The findings of the health checks that read the experiment, its flag, its linked metrics, and the
changes of the flag's split since launch and the flag's recent calls, as far as `reader_access` allows."""
- experiment = (
- ExperimentModel.objects.filter(team_id=team_id)
- .select_related("team", "feature_flag")
- .prefetch_related("experimenttosavedmetric_set")
- .get(id=experiment_id)
+ context = load_experiment_health_context(team_id=team_id, experiment_id=experiment_id, reader_access=reader_access)
+ return evaluate_health(context, EXPERIMENT_HEALTH_CHECKS)
+
+
+def get_experiment_health_inputs(
+ *, team_id: int, experiment_id: int, reader_access: ExperimentHealthReaderAccess, user: User | None
+) -> dict[str, Any]:
+ """Everything the health checks read for the reader, as plain data in the shape of the staff `health_inputs`
+ response: the checks' context, the exposure query's answer that the exposure checks read, and the project's
+ experiment defaults and SDK profile."""
+ inputs = load_experiment_health_inputs(
+ team_id=team_id, experiment_id=experiment_id, reader_access=reader_access, user=user
)
- split_history = load_split_history(experiment, reader_access=reader_access)
- context = load_health_context(experiment, split_history=split_history)
- traffic = load_condition_set_traffic(experiment, context, reader_access=reader_access)
- return evaluate_health(replace(context, condition_set_traffic=traffic), EXPERIMENT_HEALTH_CHECKS)
+ return health_inputs_payload(inputs)
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 5003f8b89b44..ba2f1b0ccf9b 100644
--- a/products/experiments/backend/facade/contracts.py
+++ b/products/experiments/backend/facade/contracts.py
@@ -111,6 +111,30 @@ class ExperimentHealthFindingCode(LabeledStrEnum):
SPLIT_CHANGED_MID_RUN = "split_changed_mid_run"
+class HealthExposureInputsStatus(LabeledStrEnum):
+ READY = "ready"
+ # The cached answer is past its age. A recalculation runs in the background, or the last one failed.
+ STALE = "stale"
+ # No cached answer. A calculation runs in the background.
+ CALCULATING = "calculating"
+ NOT_LAUNCHED = "not_launched"
+ NO_QUERY_ACCESS = "no_query_access"
+ # The query could not be built, or no answer is cached and the last background calculation failed.
+ FAILED = "failed"
+
+
+class ExperimentHealthInputsTrafficStatus(LabeledStrEnum):
+ READ = "read"
+ NOT_NEEDED = "not_needed"
+ NO_QUERY_ACCESS = "no_query_access"
+ # The reader is denied a flag call property that the scan reads.
+ DENIED_PROPERTIES = "denied_properties"
+ NO_FLAG_VERSION = "no_flag_version"
+ # The scan failed or was too expensive, which is cached so that it does not run again on every load. Or another
+ # request's scan was still running and did not answer in time.
+ UNKNOWN = "unknown"
+
+
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
diff --git a/products/experiments/backend/health/condition_set_traffic.py b/products/experiments/backend/health/condition_set_traffic.py
index 4d49778b089b..193c160476e1 100644
--- a/products/experiments/backend/health/condition_set_traffic.py
+++ b/products/experiments/backend/health/condition_set_traffic.py
@@ -80,7 +80,7 @@ def load_condition_set_traffic(
"""
if (
not reader_access.can_query_events
- or reader_access.denied_event_properties & _SCANNED_PROPERTIES
+ or denied_scanned_properties(reader_access)
or not needs_condition_set_traffic(ctx)
):
return None
@@ -91,6 +91,11 @@ def load_condition_set_traffic(
return None
+def denied_scanned_properties(reader_access: ExperimentHealthReaderAccess) -> frozenset[str]:
+ """The properties that the scan reads and that the reader is denied. The scan does not run when there are any."""
+ return reader_access.denied_event_properties & _SCANNED_PROPERTIES
+
+
def query_condition_set_traffic(
experiment: Experiment, *, window_start: datetime, window_end: datetime
) -> ConditionSetTraffic:
diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.py
index df3fdef0be77..df12b3dbcacd 100644
--- a/products/experiments/backend/health/context.py
+++ b/products/experiments/backend/health/context.py
@@ -33,6 +33,8 @@ class SplitHistory:
launched_at: datetime
team_timezone: str
+ # Every split change since launch. The counted changes are its tail.
+ changes: tuple[SplitChange, ...]
# From the first change with an exposure before it, or with an unknown answer, to the last change.
# Empty when nobody was exposed before any change: those changes moved nobody.
counted_changes: tuple[SplitChange, ...]
diff --git a/products/experiments/backend/health/exposure_gate.py b/products/experiments/backend/health/exposure_gate.py
index 997eb567d032..738a88864a0f 100644
--- a/products/experiments/backend/health/exposure_gate.py
+++ b/products/experiments/backend/health/exposure_gate.py
@@ -263,6 +263,7 @@ def _load_split_history(
return SplitHistory(
launched_at=launched_at,
team_timezone=team_timezone,
+ changes=(),
counted_changes=(),
exposed_before_first=False,
exposed_between=None,
@@ -293,6 +294,7 @@ def _load_split_history(
return SplitHistory(
launched_at=launched_at,
team_timezone=team_timezone,
+ changes=changes,
counted_changes=counted,
exposed_before_first=exposed_before_first,
exposed_between=exposed_between,
diff --git a/products/experiments/backend/health/exposure_inputs.py b/products/experiments/backend/health/exposure_inputs.py
new file mode 100644
index 000000000000..e103ff01f03b
--- /dev/null
+++ b/products/experiments/backend/health/exposure_inputs.py
@@ -0,0 +1,119 @@
+from datetime import datetime
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import CachedExperimentExposureQueryResponse, ExperimentExposureHealthFinding
+
+from posthog.clickhouse.client.execute_async import QueryNotFoundError, get_query_status
+from posthog.dataclasses import frozen
+from posthog.errors import internal_ch_error_user_message
+from posthog.exceptions_capture import capture_exception
+from posthog.hogql_queries.query_runner import ExecutionMode
+from posthog.models.user import User
+
+from products.experiments.backend.facade.contracts import HealthExposureInputsStatus
+from products.experiments.backend.health.context import ExposureTotals
+from products.experiments.backend.hogql_queries.experiment_exposures_query_runner import (
+ ExperimentExposuresQueryRunner,
+ build_experiment_exposure_query,
+)
+from products.experiments.backend.hogql_queries.experiment_query_builder import get_exposure_config_params_for_builder
+from products.experiments.backend.models.experiment import Experiment
+
+
+@frozen
+class ExposureInputs:
+ """The exposure query's answer that the exposure checks of the health engine read, and their findings on it."""
+
+ status: HealthExposureInputsStatus
+ # When the answer was computed. None without an answer.
+ computed_at: datetime | None
+ totals: ExposureTotals | None
+ findings: tuple[ExperimentExposureHealthFinding, ...]
+ # Why the query or its last background calculation failed. Set for FAILED, and for STALE when the recalculation
+ # failed.
+ error: str | None
+
+
+def load_exposure_inputs(experiment: Experiment, *, user: User | None, can_query_events: bool) -> ExposureInputs:
+ """
+ Reads the cached answer of the experiment's exposure query. A missing or stale answer starts a calculation in the
+ background instead of blocking, because the query can run for minutes. Never raises.
+ """
+ if experiment.start_date is None:
+ return _without_answer(HealthExposureInputsStatus.NOT_LAUNCHED)
+ if not can_query_events:
+ return _without_answer(HealthExposureInputsStatus.NO_QUERY_ACCESS)
+ try:
+ # Malformed stored exposure criteria fail here, and that must not fail the other inputs.
+ query = build_experiment_exposure_query(experiment)
+ runner = ExperimentExposuresQueryRunner(query=query, team=experiment.team, user=user, error_event_context=None)
+ calculation_error = _background_calculation_error(runner)
+ response = runner.run(
+ # A new calculation replaces the status of the failed one, which hides its error. The status expires after
+ # QueryStatusManager.STATUS_TTL_SECONDS, and a later request starts a new calculation then.
+ execution_mode=(
+ ExecutionMode.CACHE_ONLY_NEVER_CALCULATE
+ if calculation_error is not None
+ else ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE
+ ),
+ user=user,
+ )
+ except Exception as error:
+ # A running experiment whose flag lost its variants raises a ValidationError, which is expected.
+ if not isinstance(error, ValidationError):
+ capture_exception(error)
+ return _without_answer(HealthExposureInputsStatus.FAILED, error=_error_message(error))
+ if not isinstance(response, CachedExperimentExposureQueryResponse):
+ if calculation_error is not None:
+ return _without_answer(HealthExposureInputsStatus.FAILED, error=calculation_error)
+ return _without_answer(HealthExposureInputsStatus.CALCULATING)
+
+ recalculating = response.query_status is not None and not response.query_status.complete
+ srm = response.sample_ratio_mismatch
+ computed_at = response.last_refresh
+ return ExposureInputs(
+ status=(
+ HealthExposureInputsStatus.STALE
+ if recalculating or calculation_error is not None
+ else HealthExposureInputsStatus.READY
+ ),
+ computed_at=computed_at,
+ totals=ExposureTotals(
+ # The schema types the counts as floats, but the runner computes whole people.
+ total_exposures={variant: int(count) for variant, count in response.total_exposures.items()},
+ # The runner resolves the handling the same way when it computes the answer.
+ multiple_variant_handling=get_exposure_config_params_for_builder(
+ query.exposure_criteria, experiment.team, experiment.start_date
+ ).multiple_variant_handling,
+ sample_ratio_mismatch_p_value=srm.p_value if srm else None,
+ # The checks read the hours at computation, not now.
+ hours_since_launch=(computed_at - experiment.start_date).total_seconds() / 3600 if computed_at else None,
+ ),
+ findings=tuple(response.health_findings or ()),
+ error=calculation_error,
+ )
+
+
+def _background_calculation_error(runner: ExperimentExposuresQueryRunner) -> str | None:
+ """Why the last background calculation of the runner's query failed, while its status is kept."""
+ try:
+ # The runner starts a background calculation with the cache key as its id.
+ status = get_query_status(team_id=runner.team.pk, query_id=runner.get_cache_key())
+ except QueryNotFoundError:
+ return None
+ if not status.error:
+ return None
+ # The same user-safe copy that the query status endpoint serves.
+ return status.error_message or internal_ch_error_user_message(status.error_code) or "The calculation failed."
+
+
+def _without_answer(status: HealthExposureInputsStatus, *, error: str | None = None) -> ExposureInputs:
+ return ExposureInputs(status=status, computed_at=None, totals=None, findings=(), error=error)
+
+
+def _error_message(error: Exception) -> str:
+ if isinstance(error, ValidationError):
+ details = error.detail if isinstance(error.detail, list) else [error.detail]
+ return " ".join(str(detail) for detail in details)
+ return str(error)
diff --git a/products/experiments/backend/health/inputs_payload.py b/products/experiments/backend/health/inputs_payload.py
new file mode 100644
index 000000000000..59b188b0cea7
--- /dev/null
+++ b/products/experiments/backend/health/inputs_payload.py
@@ -0,0 +1,142 @@
+from dataclasses import asdict
+from typing import Any
+
+from products.experiments.backend.facade.contracts import ExperimentHealthInputsTrafficStatus
+from products.experiments.backend.health.checks.forced_variant import needs_condition_set_traffic
+from products.experiments.backend.health.condition_set_traffic import denied_scanned_properties
+from products.experiments.backend.health.context import (
+ ConditionSetTraffic,
+ FlagState,
+ Split,
+ SplitHistory,
+ SplitHistoryNotChecked,
+)
+from products.experiments.backend.health.exposure_inputs import ExposureInputs
+from products.experiments.backend.health.loader import HealthInputs
+
+
+def _health_inputs_split(split: Split) -> list[dict[str, Any]]:
+ return [{"key": variant.key, "rollout_percentage": variant.rollout_percentage} for variant in split]
+
+
+def _health_inputs_flag(flag: FlagState) -> dict[str, Any]:
+ reachable = {condition.number: condition for condition in flag.reachable_conditions}
+ return {
+ "active": flag.active,
+ "deleted": flag.deleted,
+ "release_conditions": [
+ {
+ "number": number,
+ "rollout_percentage": group.rollout_percentage,
+ "property_count": group.property_count,
+ "reachable": number in reachable,
+ "pinned_variant": reachable[number].pinned_variant if number in reachable else None,
+ }
+ for number, group in enumerate(flag.release_groups, start=1)
+ ],
+ "variants": _health_inputs_split(flag.variants),
+ }
+
+
+def _health_inputs_split_history(history: SplitHistory | SplitHistoryNotChecked) -> dict[str, Any]:
+ if isinstance(history, SplitHistory):
+ # The counted changes are the tail of every change, so their count marks where counting starts.
+ first_counted = len(history.changes) - len(history.counted_changes)
+ reason, exposed_before_first, exposed_between = None, history.exposed_before_first, history.exposed_between
+ else:
+ first_counted = len(history.changes)
+ reason, exposed_before_first, exposed_between = history.reason.value, None, None
+ return {
+ "checked": reason is None,
+ "not_checked_reason": reason,
+ "launched_at": history.launched_at,
+ "team_timezone": history.team_timezone,
+ "changes": [
+ {
+ "changed_at": change.changed_at,
+ "before": _health_inputs_split(change.before),
+ "after": _health_inputs_split(change.after),
+ "counted": index >= first_counted,
+ }
+ for index, change in enumerate(history.changes)
+ ],
+ "exposed_before_first": exposed_before_first,
+ "exposed_between": exposed_between,
+ }
+
+
+def _health_inputs_traffic(traffic: ConditionSetTraffic) -> dict[str, Any]:
+ return {
+ "since": traffic.since,
+ "team_timezone": traffic.team_timezone,
+ "people_by_set": [
+ {"condition_set": condition_set, "people": people}
+ for condition_set, people in sorted(traffic.people_by_set.items())
+ ],
+ "calls": traffic.calls,
+ "remotely_evaluated_calls": traffic.remotely_evaluated_calls,
+ }
+
+
+def _health_inputs_traffic_status(inputs: HealthInputs) -> ExperimentHealthInputsTrafficStatus:
+ ctx = inputs.context
+ # Mirrors the order of the early returns in `load_condition_set_traffic`.
+ if ctx.condition_set_traffic is not None:
+ return ExperimentHealthInputsTrafficStatus.READ
+ if not needs_condition_set_traffic(ctx):
+ return ExperimentHealthInputsTrafficStatus.NOT_NEEDED
+ if not inputs.reader_access.can_query_events:
+ return ExperimentHealthInputsTrafficStatus.NO_QUERY_ACCESS
+ if denied_scanned_properties(inputs.reader_access):
+ return ExperimentHealthInputsTrafficStatus.DENIED_PROPERTIES
+ if inputs.flag_version is None:
+ return ExperimentHealthInputsTrafficStatus.NO_FLAG_VERSION
+ return ExperimentHealthInputsTrafficStatus.UNKNOWN
+
+
+def _health_inputs_exposures(exposures: ExposureInputs) -> dict[str, Any]:
+ totals = exposures.totals
+ return {
+ "status": exposures.status,
+ "computed_at": exposures.computed_at,
+ "totals": {
+ "total_exposures": dict(totals.total_exposures),
+ "multiple_variant_handling": totals.multiple_variant_handling.value,
+ "sample_ratio_mismatch_p_value": totals.sample_ratio_mismatch_p_value,
+ "hours_since_launch": totals.hours_since_launch,
+ }
+ if totals
+ else None,
+ "findings": [finding.model_dump(mode="json") for finding in exposures.findings],
+ "error": exposures.error,
+ }
+
+
+def health_inputs_payload(inputs: HealthInputs) -> dict[str, Any]:
+ """The inputs as plain data in the shape of `ExperimentHealthInputsSerializer`, so the presentation layer renders
+ them without reading the health package's types."""
+ ctx, reader_access = inputs.context, inputs.reader_access
+ return {
+ "is_launched": ctx.is_launched,
+ "is_running": ctx.is_running,
+ "has_ended": ctx.has_ended,
+ "is_paused": ctx.is_paused,
+ "archived": ctx.archived,
+ "baseline_variant_key": ctx.baseline_variant_key,
+ "excluded_variant_keys": sorted(ctx.excluded_variant_keys),
+ "primary_metric_count": ctx.primary_metric_count,
+ "secondary_metric_count": ctx.secondary_metric_count,
+ "flag": _health_inputs_flag(ctx.flag) if ctx.flag else None,
+ "split_history": _health_inputs_split_history(ctx.split_history) if ctx.split_history else None,
+ "condition_set_traffic_status": _health_inputs_traffic_status(inputs),
+ "condition_set_traffic": _health_inputs_traffic(ctx.condition_set_traffic)
+ if ctx.condition_set_traffic
+ else None,
+ "reader_access": {
+ "can_read_flag_history": reader_access.can_read_flag_history,
+ "can_query_events": reader_access.can_query_events,
+ "denied_event_properties": sorted(reader_access.denied_event_properties),
+ },
+ "exposures": _health_inputs_exposures(inputs.exposures),
+ "project": asdict(inputs.project),
+ }
diff --git a/products/experiments/backend/health/loader.py b/products/experiments/backend/health/loader.py
new file mode 100644
index 000000000000..76b99fb989d5
--- /dev/null
+++ b/products/experiments/backend/health/loader.py
@@ -0,0 +1,65 @@
+from dataclasses import replace
+
+from posthog.dataclasses import frozen
+from posthog.models.user import User
+
+from products.experiments.backend.facade.contracts import ExperimentHealthReaderAccess
+from products.experiments.backend.health.condition_set_traffic import load_condition_set_traffic
+from products.experiments.backend.health.context import HealthContext, load_health_context
+from products.experiments.backend.health.exposure_gate import load_split_history
+from products.experiments.backend.health.exposure_inputs import ExposureInputs, load_exposure_inputs
+from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.setup_context import ProjectSetupFacts, build_project_setup_facts
+
+
+@frozen
+class HealthInputs:
+ """What the staff view of the health checks shows: the context the checks read, the exposure query's answer that
+ the exposure checks read, and facts about the project that no check reads yet but that explain a finding."""
+
+ context: HealthContext
+ exposures: ExposureInputs
+ reader_access: ExperimentHealthReaderAccess
+ # None when the experiment has no flag, or the flag has no version.
+ flag_version: int | None
+ project: ProjectSetupFacts
+
+
+def load_experiment_health_context(
+ *, team_id: int, experiment_id: int, reader_access: ExperimentHealthReaderAccess
+) -> HealthContext:
+ """The context that the checks of the health endpoint read: the experiment, its flag, its linked metrics, the
+ changes of the flag's split since launch and the flag's recent calls, as far as `reader_access` allows."""
+ return _health_context(_load_experiment(team_id, experiment_id), reader_access)
+
+
+def load_experiment_health_inputs(
+ *, team_id: int, experiment_id: int, reader_access: ExperimentHealthReaderAccess, user: User | None
+) -> HealthInputs:
+ experiment = _load_experiment(team_id, experiment_id)
+ return HealthInputs(
+ context=_health_context(experiment, reader_access),
+ exposures=load_exposure_inputs(experiment, user=user, can_query_events=reader_access.can_query_events),
+ reader_access=reader_access,
+ flag_version=experiment.feature_flag.version if experiment.feature_flag_id else None,
+ project=build_project_setup_facts(
+ experiment.team,
+ can_query_events=reader_access.can_query_events,
+ denied_event_properties=reader_access.denied_event_properties,
+ ),
+ )
+
+
+def _load_experiment(team_id: int, experiment_id: int) -> Experiment:
+ return (
+ Experiment.objects.select_related("team", "feature_flag")
+ .prefetch_related("experimenttosavedmetric_set")
+ .get(id=experiment_id, team_id=team_id)
+ )
+
+
+def _health_context(experiment: Experiment, reader_access: ExperimentHealthReaderAccess) -> HealthContext:
+ split_history = load_split_history(experiment, reader_access=reader_access)
+ context = load_health_context(experiment, split_history=split_history)
+ traffic = load_condition_set_traffic(experiment, context, reader_access=reader_access)
+ return replace(context, condition_set_traffic=traffic)
diff --git a/products/experiments/backend/health/test/test_exposure_inputs.py b/products/experiments/backend/health/test/test_exposure_inputs.py
new file mode 100644
index 000000000000..388252197d89
--- /dev/null
+++ b/products/experiments/backend/health/test/test_exposure_inputs.py
@@ -0,0 +1,158 @@
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ CachedExperimentExposureQueryResponse,
+ CacheMissResponse,
+ DateRange,
+ QueryStatus,
+ SampleRatioMismatch,
+)
+
+from posthog.clickhouse.client.execute_async import QueryStatusManager, get_query_status
+
+from products.experiments.backend.facade.contracts import HealthExposureInputsStatus
+from products.experiments.backend.health.exposure_inputs import load_exposure_inputs
+from products.experiments.backend.hogql_queries.experiment_exposures_query_runner import (
+ ExperimentExposuresQueryRunner,
+ build_experiment_exposure_query,
+)
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+LAUNCHED_AT = datetime(2026, 10, 1, 12, tzinfo=UTC)
+COMPUTED_AT = LAUNCHED_AT + timedelta(hours=30)
+CALCULATION_ERROR = "The exposure criteria name an event property that does not exist."
+
+
+def _cached_answer(*, recalculating: bool) -> CachedExperimentExposureQueryResponse:
+ return CachedExperimentExposureQueryResponse(
+ cache_key="exposures",
+ date_range=DateRange(date_from=LAUNCHED_AT.isoformat()),
+ is_cached=True,
+ last_refresh=COMPUTED_AT,
+ next_allowed_client_refresh=COMPUTED_AT,
+ timeseries=[],
+ timezone="UTC",
+ total_exposures={"control": 480, "test": 520},
+ sample_ratio_mismatch=SampleRatioMismatch(expected={"control": 500, "test": 500}, p_value=0.2),
+ query_status=QueryStatus(id="q", team_id=1, complete=False) if recalculating else None,
+ )
+
+
+class TestLoadExposureInputs(BaseTest):
+ def _create_experiment(self, key: str) -> Experiment:
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key=key,
+ created_by=self.user,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ return Experiment.objects.create(team=self.team, name=key, feature_flag=flag, start_date=LAUNCHED_AT)
+
+ def _store_failed_calculation(self, experiment: Experiment) -> str:
+ runner = ExperimentExposuresQueryRunner(
+ query=build_experiment_exposure_query(experiment), team=self.team, user=self.user, error_event_context=None
+ )
+ cache_key = runner.get_cache_key()
+ QueryStatusManager(cache_key, self.team.pk).store_query_status(
+ QueryStatus(id=cache_key, team_id=self.team.pk, complete=True, error=True, error_message=CALCULATION_ERROR)
+ )
+ return cache_key
+
+ @parameterized.expand(
+ [
+ ("fresh_answer", _cached_answer(recalculating=False), False, HealthExposureInputsStatus.READY, True),
+ ("stale_answer", _cached_answer(recalculating=True), False, HealthExposureInputsStatus.STALE, True),
+ (
+ "answer_after_a_failed_refresh",
+ _cached_answer(recalculating=False),
+ True,
+ HealthExposureInputsStatus.STALE,
+ True,
+ ),
+ (
+ "no_answer",
+ CacheMissResponse(cache_key="exposures"),
+ False,
+ HealthExposureInputsStatus.CALCULATING,
+ False,
+ ),
+ ]
+ )
+ def test_reads_what_the_exposure_checks_read_from_the_cached_answer(
+ self,
+ _name: str,
+ response: CachedExperimentExposureQueryResponse | CacheMissResponse,
+ refresh_failed: bool,
+ expected_status: HealthExposureInputsStatus,
+ has_totals: bool,
+ ) -> None:
+ experiment = self._create_experiment(f"exposure-inputs-{_name}")
+ if refresh_failed:
+ self._store_failed_calculation(experiment)
+
+ with patch(
+ "products.experiments.backend.health.exposure_inputs.ExperimentExposuresQueryRunner.run",
+ return_value=response,
+ ):
+ inputs = load_exposure_inputs(experiment, user=self.user, can_query_events=True)
+
+ self.assertEqual(
+ (inputs.status, inputs.error), (expected_status, CALCULATION_ERROR if refresh_failed else None)
+ )
+ if not has_totals:
+ self.assertIsNone(inputs.totals)
+ return
+ assert inputs.totals is not None
+ self.assertEqual(
+ (
+ dict(inputs.totals.total_exposures),
+ inputs.totals.sample_ratio_mismatch_p_value,
+ inputs.totals.hours_since_launch,
+ ),
+ ({"control": 480, "test": 520}, 0.2, 30.0),
+ )
+
+ def test_reports_failed_for_malformed_exposure_criteria(self) -> None:
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="exposure-inputs-malformed",
+ created_by=self.user,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ },
+ )
+ experiment = Experiment.objects.create(
+ team=self.team,
+ name="exposure-inputs-malformed",
+ feature_flag=flag,
+ start_date=LAUNCHED_AT,
+ exposure_criteria={"multiple_variant_handling": "not_a_handling"},
+ )
+
+ inputs = load_exposure_inputs(experiment, user=self.user, can_query_events=True)
+
+ self.assertEqual(inputs.status, HealthExposureInputsStatus.FAILED)
+
+ def test_reports_a_failed_calculation_and_does_not_start_another(self) -> None:
+ experiment = self._create_experiment("exposure-inputs-failed-calculation")
+ cache_key = self._store_failed_calculation(experiment)
+
+ inputs = load_exposure_inputs(experiment, user=self.user, can_query_events=True)
+
+ self.assertEqual((inputs.status, inputs.error), (HealthExposureInputsStatus.FAILED, CALCULATION_ERROR))
+ self.assertEqual(get_query_status(team_id=self.team.pk, query_id=cache_key).error_message, CALCULATION_ERROR)
diff --git a/products/experiments/backend/health/test/test_split_changed.py b/products/experiments/backend/health/test/test_split_changed.py
index 763115fcb691..4a7567e7c62a 100644
--- a/products/experiments/backend/health/test/test_split_changed.py
+++ b/products/experiments/backend/health/test/test_split_changed.py
@@ -79,6 +79,7 @@ def _context(
split_history=SplitHistory(
launched_at=launched_at,
team_timezone="Europe/Berlin",
+ changes=changes,
counted_changes=changes,
exposed_before_first=exposed_before_first,
exposed_between=exposed_between,
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 8111f34257da..6974299bd4a8 100644
--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
@@ -60,6 +60,29 @@ QUERY_ROW_LIMIT = 5000 # The result has one row per (day, variant) pair
SRM_MINIMUM_SAMPLE_SIZE = 100 # Minimum total exposures required for SRM calculation
+def build_experiment_exposure_query(experiment: Experiment) -> ExperimentExposureQuery:
+ """The exposure query of an experiment over its own window. Backend callers build it here, so they share one
+ cache entry. The page builds its own, with the whole flag, so it caches apart."""
+ feature_flag = experiment.feature_flag
+ # The FK gives a model instance, and the query field is a pydantic type with no
+ # attribute-based validation, so it must be serialized first.
+ experiment_holdout = experiment.holdout
+ holdout = (
+ {"id": experiment_holdout.id, "name": experiment_holdout.name, "filters": experiment_holdout.filters}
+ if experiment_holdout is not None
+ else None
+ )
+ return ExperimentExposureQuery(
+ experiment_id=experiment.id,
+ experiment_name=experiment.name,
+ feature_flag={"key": feature_flag.key, "filters": feature_flag.filters},
+ start_date=experiment.start_date.isoformat() if experiment.start_date else None,
+ end_date=experiment.end_date.isoformat() if experiment.end_date else None,
+ exposure_criteria=experiment.exposure_criteria,
+ holdout=holdout,
+ )
+
+
class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
query: ExperimentExposureQuery
cached_response: CachedExperimentExposureQueryResponse
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 55d8ca143ab7..7b352f490fa5 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -48,6 +48,8 @@ from products.experiments.backend.facade.contracts import (
ExperimentHealthFindingActionKind,
ExperimentHealthFindingCode,
ExperimentHealthFindingSeverity,
+ ExperimentHealthInputsTrafficStatus,
+ HealthExposureInputsStatus,
)
from products.experiments.backend.facade.timeseries import METRIC_BUILDERS, apply_saved_metric_overrides
from products.experiments.backend.hogql_queries.exposure_query_logic import resolve_default_exposure_event
@@ -3108,3 +3110,227 @@ class ExperimentSetupContextResponseSerializer(serializers.Serializer):
help_text="Recent experiments in the project."
)
shared_metrics = ExperimentSetupSharedMetricsSectionSerializer(help_text="Most reused shared metrics.")
+
+
+class ExperimentHealthInputsVariantSerializer(serializers.Serializer):
+ key = serializers.CharField(allow_null=True, help_text="The variant key. Null when the flag stores no string key.")
+ rollout_percentage = serializers.FloatField(
+ allow_null=True, help_text="The variant's share of the split, in percent. Null when the flag stores no number."
+ )
+
+
+class ExperimentHealthInputsReleaseConditionSerializer(serializers.Serializer):
+ number = serializers.IntegerField(
+ help_text="The condition's position in the flag, from 1, as the flag page labels it ('Set 2')."
+ )
+ rollout_percentage = serializers.FloatField(
+ allow_null=True, help_text="The condition's rollout, in percent. Null when the flag stores no number."
+ )
+ property_count = serializers.IntegerField(
+ allow_null=True, help_text="The number of property filters. Null when the flag stores no list."
+ )
+ reachable = serializers.BooleanField(
+ help_text="Whether the condition can serve a request. A condition after one that matches everyone never does."
+ )
+ pinned_variant = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "The variant that the condition's override serves. Null when the condition is not reachable, has no "
+ "override, or its override names no variant of the flag."
+ ),
+ )
+
+
+class ExperimentHealthInputsFlagSerializer(serializers.Serializer):
+ active = serializers.BooleanField(help_text="Whether the flag is enabled.")
+ deleted = serializers.BooleanField(help_text="Whether the flag is deleted.")
+ release_conditions = ExperimentHealthInputsReleaseConditionSerializer(
+ many=True, help_text="The flag's release conditions, in evaluation order."
+ )
+ variants = ExperimentHealthInputsVariantSerializer(many=True, help_text="The flag's variants and their split.")
+
+
+class ExperimentHealthInputsSplitChangeSerializer(serializers.Serializer):
+ changed_at = serializers.DateTimeField(help_text="When the flag's split changed.")
+ before = ExperimentHealthInputsVariantSerializer(many=True, help_text="The split before the change.")
+ after = ExperimentHealthInputsVariantSerializer(many=True, help_text="The split after the change.")
+ counted = serializers.BooleanField(
+ help_text=(
+ "Whether the split-change check counts this change: it and every later change count from the first "
+ "with an exposure before it, or an unknown answer. False for every change when not checked."
+ )
+ )
+
+
+class ExperimentHealthInputsSplitHistorySerializer(serializers.Serializer):
+ checked = serializers.BooleanField(
+ help_text="Whether the split changes were compared with the exposures. False when not_checked_reason is set."
+ )
+ not_checked_reason = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Why the split changes were not compared with the exposures: 'no_history_access', 'no_query_access', "
+ "'exposure_filters', 'exposure_action' or 'exposure_criteria'. Null when they were."
+ ),
+ )
+ launched_at = serializers.DateTimeField(help_text="When the experiment launched.")
+ team_timezone = serializers.CharField(help_text="The project's time zone, which the finding uses for times.")
+ changes = ExperimentHealthInputsSplitChangeSerializer(
+ many=True,
+ help_text="Every split change since launch. Empty for 'no_history_access', which does not read them.",
+ )
+ exposed_before_first = serializers.BooleanField(
+ allow_null=True,
+ help_text="Whether anyone was exposed before the first counted change. Null when unknown or not checked.",
+ )
+ exposed_between = serializers.BooleanField(
+ allow_null=True,
+ help_text=(
+ "Whether anyone was exposed between the first and the last change. Asked only when the last change "
+ "restores the split from before the first. Null when not asked or unknown."
+ ),
+ )
+
+
+class ExperimentHealthInputsConditionSetPeopleSerializer(serializers.Serializer):
+ condition_set = serializers.IntegerField(help_text="The number of the release condition, from 1.")
+ people = serializers.IntegerField(help_text="The people whose latest call this condition served.")
+
+
+class ExperimentHealthInputsConditionSetTrafficSerializer(serializers.Serializer):
+ since = serializers.DateTimeField(
+ help_text="The start of the window: the latest of launch, the flag's last save and 7 days ago."
+ )
+ team_timezone = serializers.CharField(help_text="The project's time zone, which the finding uses for times.")
+ people_by_set = ExperimentHealthInputsConditionSetPeopleSerializer(
+ many=True, help_text="People by the release condition that served their latest call of the flag's version."
+ )
+ calls = serializers.IntegerField(help_text="The flag's calls in the window, of any flag version.")
+ remotely_evaluated_calls = serializers.IntegerField(
+ help_text=(
+ "The calls that the flag service evaluated. Only those name a condition set. Local evaluation in a "
+ "server SDK and a bootstrapped value name none."
+ )
+ )
+
+
+class ExperimentHealthInputsReaderAccessSerializer(serializers.Serializer):
+ can_read_flag_history = serializers.BooleanField(
+ help_text="Whether the reader may read the flag's history, which the split-change check needs."
+ )
+ can_query_events = serializers.BooleanField(
+ help_text="Whether the reader may query events, which the split-change and forced-variant checks need."
+ )
+ denied_event_properties = serializers.ListField(
+ child=serializers.CharField(),
+ help_text=(
+ "Event properties the reader is denied. The forced-variant check skips its scan when one of them is a "
+ "flag call property it reads."
+ ),
+ )
+
+
+class ExperimentHealthInputsExposureTotalsSerializer(serializers.Serializer):
+ total_exposures = serializers.DictField(
+ child=serializers.IntegerField(),
+ help_text="Exposed people by variant. '$multiple' counts the people exposed to more than one variant.",
+ )
+ multiple_variant_handling = serializers.CharField(
+ help_text="How the analysis treats people in several variants: 'exclude' or 'first_seen'."
+ )
+ sample_ratio_mismatch_p_value = serializers.FloatField(
+ allow_null=True, help_text="The p-value of the sample ratio test. Null when there was too little data."
+ )
+ hours_since_launch = serializers.FloatField(
+ allow_null=True, help_text="Hours from launch to the computation of the answer, as the checks read them."
+ )
+
+
+class ExperimentHealthInputsExposuresSerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=HealthExposureInputsStatus.choices,
+ help_text=(
+ "Whether a cached answer was read. 'calculating' means no answer is cached and a calculation runs in the "
+ "background, so a later request reads a fresh answer. 'stale' means the cached answer is past its age: a "
+ "recalculation runs in the background, or the last one failed and 'error' says why. After a failed "
+ "calculation, no new one starts for 20 minutes."
+ ),
+ )
+ computed_at = serializers.DateTimeField(allow_null=True, help_text="When the answer was computed.")
+ totals = ExperimentHealthInputsExposureTotalsSerializer(
+ allow_null=True, help_text="What the exposure checks read. Null without an answer."
+ )
+ findings = ExperimentHealthFindingSerializer(
+ many=True, help_text="The findings of the exposure checks on this answer: zero exposures, SRM and bias risk."
+ )
+ error = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Why the query or its last background calculation failed. Set for 'failed', and for 'stale' when the "
+ "recalculation failed."
+ ),
+ )
+
+
+class ExperimentHealthInputsProjectSerializer(serializers.Serializer):
+ team_defaults = ExperimentSetupTeamDefaultsSectionSerializer(help_text="The project's experiment defaults.")
+ sdk_profile = ExperimentSetupSdkProfileSectionSerializer(
+ help_text=(
+ "Which SDKs call feature flags and where flags are evaluated, across the whole project. Skipped for a "
+ "reader who may not query events."
+ )
+ )
+
+
+class ExperimentHealthInputsSerializer(serializers.Serializer):
+ is_launched = serializers.BooleanField(help_text="Whether the experiment has a start date.")
+ is_running = serializers.BooleanField(help_text="Whether the experiment is launched and not ended.")
+ has_ended = serializers.BooleanField(help_text="Whether the experiment has an end date.")
+ is_paused = serializers.BooleanField(help_text="Whether the experiment is paused.")
+ archived = serializers.BooleanField(help_text="Whether the experiment is archived.")
+ baseline_variant_key = serializers.CharField(
+ allow_null=True, help_text="The baseline set in the experiment's settings. Null when unset."
+ )
+ excluded_variant_keys = serializers.ListField(
+ child=serializers.CharField(),
+ help_text=(
+ "The variants the analysis leaves out of the results. The forced-variant check ignores pins to them."
+ ),
+ )
+ primary_metric_count = serializers.IntegerField(
+ help_text="Single-use primary metrics plus shared metrics linked as primary."
+ )
+ secondary_metric_count = serializers.IntegerField(
+ help_text="Single-use secondary metrics plus shared metrics linked as secondary."
+ )
+ flag = ExperimentHealthInputsFlagSerializer(
+ allow_null=True, help_text="The experiment's feature flag. Null when it has none."
+ )
+ split_history = ExperimentHealthInputsSplitHistorySerializer(
+ allow_null=True,
+ help_text=(
+ "The changes of the flag's split since launch. Null when the experiment is not running, is archived, "
+ "its flag is missing or deleted, or the read failed."
+ ),
+ )
+ condition_set_traffic_status = serializers.ChoiceField(
+ choices=ExperimentHealthInputsTrafficStatus.choices,
+ help_text=(
+ "Whether the condition-set traffic was read, or why not. The forced-variant check needs it when the "
+ "experiment is launched and some but not all release conditions pin a variant that has a share of the "
+ "split and is not excluded from the analysis."
+ ),
+ )
+ condition_set_traffic = ExperimentHealthInputsConditionSetTrafficSerializer(
+ allow_null=True,
+ help_text="The flag's recent calls by condition set. Null unless condition_set_traffic_status is 'read'.",
+ )
+ reader_access = ExperimentHealthInputsReaderAccessSerializer(
+ help_text="What the reader may read, which decides what the checks can load."
+ )
+ exposures = ExperimentHealthInputsExposuresSerializer(
+ help_text="The exposure query's answer that the exposure checks read, from the cache."
+ )
+ project = ExperimentHealthInputsProjectSerializer(
+ help_text="Facts about the project that no check reads yet, from the same providers as the setup context."
+ )
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 16f4e48b7c9f..870b51c8b150 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -78,7 +78,7 @@ from products.access_control.backend.facade.user_access_control import (
from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
from products.approvals.backend.mixins import ApprovalHandlingMixin
from products.experiments.backend.experiment_service import ExperimentService, ExperimentVersionConflict
-from products.experiments.backend.facade.api import get_experiment_health_findings
+from products.experiments.backend.facade.api import get_experiment_health_findings, get_experiment_health_inputs
from products.experiments.backend.facade.contracts import ExperimentHealthReaderAccess
from products.experiments.backend.facade.legacy_migration import (
LegacyMigrationError,
@@ -106,6 +106,7 @@ from products.experiments.backend.presentation.serializers import (
ExperimentBasicSerializer,
ExperimentFlagCleanupTargetSerializer,
ExperimentFlagCleanupTaskSerializer,
+ ExperimentHealthInputsSerializer,
ExperimentHealthSerializer,
ExperimentInSessionExposureSerializer,
ExperimentMatchingIdsResponseSerializer,
@@ -531,7 +532,7 @@ class EnterpriseExperimentsViewSet(
.select_related("created_by")
.defer(*LIST_DEFERRED_FIELDS)
)
- if self.action == "health":
+ if self.action in ("health", "health_inputs"):
# The facade reads the experiment again with the joins its checks need, so the object lookup
# here only checks access.
queryset = queryset.select_related(None).prefetch_related(None).select_related("team")
@@ -943,6 +944,35 @@ class EnterpriseExperimentsViewSet(
)
return Response(ExperimentHealthSerializer({"findings": findings}).data)
+ @extend_schema(
+ request=None,
+ responses=ExperimentHealthInputsSerializer,
+ )
+ @action(
+ methods=["GET"],
+ detail=True,
+ required_scopes=["experiment:read"],
+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],
+ )
+ def health_inputs(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """
+ Staff only. The inputs that the health checks read for this reader, to debug why a finding shows or not:
+ the context of the checks in `health`, the exposure query's answer that the exposure checks read, and facts
+ about the project from the setup context's providers (the team's experiment defaults and which SDKs call
+ flags). The exposure answer comes from the cache. When it is missing or stale, a calculation starts in the
+ background and `exposures.status` says so.
+ """
+ if not (request.user.is_staff or settings.DEBUG or is_impersonated_session(request)):
+ raise PermissionDenied("Only staff users can read the health check inputs.")
+ experiment: Experiment = self.get_object()
+ inputs = get_experiment_health_inputs(
+ team_id=self.team_id,
+ experiment_id=experiment.id,
+ reader_access=self._health_reader_access(request, experiment),
+ user=cast(User, request.user),
+ )
+ return Response(ExperimentHealthInputsSerializer(inputs).data)
+
def _health_reader_access(self, request: Request, experiment: Experiment) -> ExperimentHealthReaderAccess:
# The split history is flag history, which `activity` keeps behind the flag's own access controls and
# `activity_log:read`. It also queries events, which a scoped token reaches only with `query:read`.
diff --git a/products/experiments/backend/setup_context.py b/products/experiments/backend/setup_context.py
index c13a1b4d488c..3cf1c92e945d 100644
--- a/products/experiments/backend/setup_context.py
+++ b/products/experiments/backend/setup_context.py
@@ -128,6 +128,11 @@ SDK_PROFILE_WINDOW_DAYS: Final = 7
SDK_ANY_EVENT_WINDOW_DAYS: Final = 1
TARGET_WINDOW_DAYS: Final = 14
SDK_PROFILE_MAX_LIBS: Final = 10
+# The event properties that the SDK profile's queries read. Keep it in step with `_compute_sdk_profile` and
+# `_libs_on_any_event`: `build_project_setup_facts` skips the profile for a reader denied one of them.
+SDK_PROFILE_PROPERTIES: Final[frozenset[str]] = frozenset(
+ {"$feature_flag", "$feature_flag_response", "$lib", "locally_evaluated", "$device_id", "$is_identified"}
+)
TARGET_SURFACE_MAX_LIBS: Final = 5
DEFAULT_LIST_LIMIT: Final = 10
MAX_LIST_LIMIT: Final = 25
@@ -420,6 +425,29 @@ class ExperimentSetupContext:
SectionObserver = Callable[[str, SetupContextSectionStatus, float], None]
+@frozen
+class ProjectSetupFacts:
+ """The sections of the setup context that describe the project as it is, without a planned experiment."""
+
+ team_defaults: SetupContextSection[TeamDefaults]
+ sdk_profile: SetupContextSection[SdkProfile]
+
+
+def build_project_setup_facts(
+ team: Team, *, can_query_events: bool, denied_event_properties: frozenset[str]
+) -> ProjectSetupFacts:
+ """The team's experiment defaults and its SDK profile. The SDK profile queries events across the project without
+ the reader and is cached for every reader, so it is skipped for a reader who may not query events or is denied a
+ property it reads."""
+ may_read_sdk_profile = can_query_events and not (denied_event_properties & SDK_PROFILE_PROPERTIES)
+ return ProjectSetupFacts(
+ team_defaults=_run_section("team_defaults", team, lambda: get_team_defaults(team)),
+ sdk_profile=_run_section("sdk_profile", team, lambda: get_sdk_profile(team))
+ if may_read_sdk_profile
+ else SetupContextSection(status=SetupContextSectionStatus.SKIPPED),
+ )
+
+
def build_setup_context(
*,
team: Team,
diff --git a/products/experiments/backend/temporal/scheduled_recalculation_logic.py b/products/experiments/backend/temporal/scheduled_recalculation_logic.py
index 0c79b50f117f..8fc07f51f66d 100644
--- a/products/experiments/backend/temporal/scheduled_recalculation_logic.py
+++ b/products/experiments/backend/temporal/scheduled_recalculation_logic.py
@@ -322,33 +322,15 @@ def count_total_exposures(experiment: Experiment) -> int:
The `$multiple` bucket holds entities that saw more than one variant, so it is not a
variant's audience and does not count toward the threshold.
"""
- from posthog.schema import ExperimentExposureQuery # noqa: PLC0415 — keeps the schema import off the module path
-
from posthog.clickhouse.query_tagging import Product, tags_context
from posthog.hogql_queries.query_runner import ExecutionMode
from products.experiments.backend.hogql_queries.experiment_exposures_query_runner import (
ExperimentExposuresQueryRunner,
+ build_experiment_exposure_query,
)
- feature_flag = experiment.feature_flag
- # The FK gives a model instance, and the query field is a pydantic type with no
- # attribute-based validation, so it must be serialized first.
- experiment_holdout = experiment.holdout
- holdout = (
- {"id": experiment_holdout.id, "name": experiment_holdout.name, "filters": experiment_holdout.filters}
- if experiment_holdout is not None
- else None
- )
- query = ExperimentExposureQuery(
- experiment_id=experiment.id,
- experiment_name=experiment.name,
- feature_flag={"key": feature_flag.key, "filters": feature_flag.filters},
- start_date=experiment.start_date.isoformat() if experiment.start_date else None,
- end_date=experiment.end_date.isoformat() if experiment.end_date else None,
- exposure_criteria=experiment.exposure_criteria,
- holdout=holdout,
- )
+ query = build_experiment_exposure_query(experiment)
with tags_context(
product=Product.EXPERIMENTS, team_id=experiment.team_id, org_id=str(experiment.team.organization_id)
):
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index c07635fa169e..635610a9ee91 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -894,21 +894,146 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
expected_severity: str,
denied_property: str | None = None,
) -> None:
+ experiment = self._create_experiment_with_a_pinned_condition(f"health-pinned-{_name}")
+ if denied_property is not None:
+ self._deny_event_property(denied_property)
+ headers: dict[str, str] = {}
+ if token_scopes is not None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user, label="health", secure_value=hash_key_value(token), scopes=token_scopes
+ )
+ self.client.logout()
+ headers = {"authorization": f"Bearer {token}"}
+
+ with patch(
+ "products.experiments.backend.health.condition_set_traffic.query_condition_set_traffic",
+ side_effect=[traffic],
+ ):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/experiments/{experiment.id}/health/", headers=headers
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(
+ [
+ (finding["subcode"], finding["severity"])
+ for finding in response.json()["findings"]
+ if finding["code"] == "forced_variant_release_condition"
+ ],
+ [("some_conditions_pinned", expected_severity)],
+ )
+
+ @parameterized.expand(
+ [
+ ("staff_session", True, None, status.HTTP_200_OK, ("read", [120, 880], "ok", "ok")),
+ (
+ "staff_token_without_query_scope",
+ True,
+ ["experiment:read", "activity_log:read"],
+ status.HTTP_200_OK,
+ ("no_query_access", None, "ok", "skipped"),
+ ),
+ (
+ "staff_denied_a_flag_call_property",
+ True,
+ None,
+ status.HTTP_200_OK,
+ ("denied_properties", None, "ok", "ok"),
+ "$feature_flag_reason",
+ ),
+ (
+ "staff_denied_a_property_the_sdk_profile_reads",
+ True,
+ None,
+ status.HTTP_200_OK,
+ ("read", [120, 880], "ok", "skipped"),
+ "$lib",
+ ),
+ ("not_staff", False, None, status.HTTP_403_FORBIDDEN, None),
+ ]
+ )
+ def test_health_inputs_serve_what_the_checks_read_to_staff_only(
+ self,
+ _name: str,
+ is_staff: bool,
+ token_scopes: list[str] | None,
+ expected_status: int,
+ expected: tuple[str, list[int] | None, str, str] | None,
+ denied_property: str | None = None,
+ ) -> None:
+ self.user.is_staff = is_staff
+ self.user.save()
+ experiment = self._create_experiment_with_a_pinned_condition(f"health-inputs-{_name}")
+ if denied_property is not None:
+ self._deny_event_property(denied_property)
+ headers: dict[str, str] = {}
+ if token_scopes is not None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user, label="health", secure_value=hash_key_value(token), scopes=token_scopes
+ )
+ self.client.logout()
+ headers = {"authorization": f"Bearer {token}"}
+
+ with patch(
+ "products.experiments.backend.health.condition_set_traffic.query_condition_set_traffic",
+ return_value=_HEALTH_TRAFFIC,
+ ):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/experiments/{experiment.id}/health_inputs/", headers=headers
+ )
+
+ self.assertEqual(response.status_code, expected_status, response.content)
+ if expected is None:
+ return
+ inputs = response.json()
+ self.assertEqual(
+ [(condition["number"], condition["pinned_variant"]) for condition in inputs["flag"]["release_conditions"]],
+ [(1, "test"), (2, None)],
+ )
+ traffic = inputs["condition_set_traffic"]
+ self.assertEqual(
+ (
+ inputs["condition_set_traffic_status"],
+ [people["people"] for people in traffic["people_by_set"]] if traffic else None,
+ inputs["project"]["team_defaults"]["status"],
+ inputs["project"]["sdk_profile"]["status"],
+ ),
+ expected,
+ )
+
+ @parameterized.expand(
+ [
+ ("no_split_change", False, True, None, (True, None, [])),
+ ("change_before_any_exposure", True, False, None, (True, None, [False])),
+ ("change_after_an_exposure", True, True, None, (True, None, [True])),
+ (
+ "token_without_query_scope",
+ True,
+ True,
+ ["experiment:read", "activity_log:read"],
+ (False, "no_query_access", [False]),
+ ),
+ ]
+ )
+ def test_health_inputs_report_every_split_change_and_whether_it_counts(
+ self,
+ _name: str,
+ rebalance: bool,
+ exposed: bool,
+ token_scopes: list[str] | None,
+ expected: tuple[bool, str | None, list[bool]],
+ ) -> None:
+ self.user.is_staff = True
+ self.user.save()
+ start_date = timezone.now() - timedelta(days=3)
flag = FeatureFlag.objects.create(
team=self.team,
- key=f"health-pinned-{_name}",
+ key=f"health-inputs-split-{_name}",
created_by=self.user,
filters={
- "groups": [
- {
- "properties": [
- {"key": "email", "value": "@example.com", "operator": "icontains", "type": "person"}
- ],
- "rollout_percentage": 100,
- "variant": "test",
- },
- {"properties": [], "rollout_percentage": 100},
- ],
+ "groups": [{"properties": [], "rollout_percentage": 100}],
"multivariate": {
"variants": [
{"key": "control", "rollout_percentage": 50},
@@ -918,29 +1043,10 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
},
)
experiment = Experiment.objects.create(
- team=self.team,
- name="health-pinned",
- feature_flag=flag,
- start_date=timezone.now() - timedelta(days=3),
- metrics=[_HEALTH_METRIC],
+ team=self.team, name="health-inputs-split", feature_flag=flag, start_date=start_date
)
- if denied_property is not None:
- self.organization.available_product_features = [
- {"key": AvailableFeature.PROPERTY_ACCESS_CONTROL, "name": AvailableFeature.PROPERTY_ACCESS_CONTROL}
- ]
- self.organization.save()
- denied = PropertyDefinition.objects.create(
- team=self.team, name=denied_property, property_type="String", type=PropertyDefinition.Type.EVENT
- )
- upsert_property_access_control(
- team_id=self.team.id,
- created_by_id=self.user.id,
- input=UpsertPropertyAccessControlInput(
- property_definition_id=str(denied.id),
- access_level=PropertyAccessLevel.NONE,
- organization_member_id=self.organization_membership.id,
- ),
- )
+ if rebalance:
+ self._rebalance_split_at(flag, start_date + timedelta(days=1))
headers: dict[str, str] = {}
if token_scopes is not None:
token = generate_random_token_personal()
@@ -950,22 +1056,66 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
self.client.logout()
headers = {"authorization": f"Bearer {token}"}
- with patch(
- "products.experiments.backend.health.condition_set_traffic.query_condition_set_traffic",
- side_effect=[traffic],
- ):
+ with patch("products.experiments.backend.health.exposure_gate.query_any_exposure", return_value=exposed):
response = self.client.get(
- f"/api/projects/{self.team.id}/experiments/{experiment.id}/health/", headers=headers
+ f"/api/projects/{self.team.id}/experiments/{experiment.id}/health_inputs/", headers=headers
)
self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ history = response.json()["split_history"]
self.assertEqual(
- [
- (finding["subcode"], finding["severity"])
- for finding in response.json()["findings"]
- if finding["code"] == "forced_variant_release_condition"
- ],
- [("some_conditions_pinned", expected_severity)],
+ (history["checked"], history["not_checked_reason"], [change["counted"] for change in history["changes"]]),
+ expected,
+ )
+
+ def _deny_event_property(self, name: str) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.PROPERTY_ACCESS_CONTROL, "name": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ denied = PropertyDefinition.objects.create(
+ team=self.team, name=name, property_type="String", type=PropertyDefinition.Type.EVENT
+ )
+ upsert_property_access_control(
+ team_id=self.team.id,
+ created_by_id=self.user.id,
+ input=UpsertPropertyAccessControlInput(
+ property_definition_id=str(denied.id),
+ access_level=PropertyAccessLevel.NONE,
+ organization_member_id=self.organization_membership.id,
+ ),
+ )
+
+ def _create_experiment_with_a_pinned_condition(self, flag_key: str) -> Experiment:
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key=flag_key,
+ created_by=self.user,
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": "email", "value": "@example.com", "operator": "icontains", "type": "person"}
+ ],
+ "rollout_percentage": 100,
+ "variant": "test",
+ },
+ {"properties": [], "rollout_percentage": 100},
+ ],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ return Experiment.objects.create(
+ team=self.team,
+ name="health-pinned",
+ feature_flag=flag,
+ start_date=timezone.now() - timedelta(days=3),
+ metrics=[_HEALTH_METRIC],
)
def _rebalance_split_at(self, flag: FeatureFlag, at: datetime) -> None:
diff --git a/products/experiments/backend/test/test_setup_context.py b/products/experiments/backend/test/test_setup_context.py
index 84f244fb4d66..baafe8c303e3 100644
--- a/products/experiments/backend/test/test_setup_context.py
+++ b/products/experiments/backend/test/test_setup_context.py
@@ -219,6 +219,7 @@ class TestResponseCoversEveryFact(SimpleTestCase):
("PreviousExperiments", "ExperimentSetupPreviousExperimentsSerializer"),
("SharedMetricUsage", "ExperimentSetupSharedMetricSerializer"),
("SharedMetrics", "ExperimentSetupSharedMetricsSerializer"),
+ ("ProjectSetupFacts", "ExperimentHealthInputsProjectSerializer"),
]
# Inputs and internal helpers, which the response never carries.
UNRENDERED = {
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index f5e33a07ff79..a91626b487ad 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -3011,6 +3011,427 @@ export interface ExperimentFlagCleanupTaskApi {
can_view_task: boolean
}
+export interface ExperimentHealthInputsReleaseConditionApi {
+ /** The condition's position in the flag, from 1, as the flag page labels it ('Set 2'). */
+ number: number
+ /**
+ * The condition's rollout, in percent. Null when the flag stores no number.
+ * @nullable
+ */
+ rollout_percentage: number | null
+ /**
+ * The number of property filters. Null when the flag stores no list.
+ * @nullable
+ */
+ property_count: number | null
+ /** Whether the condition can serve a request. A condition after one that matches everyone never does. */
+ reachable: boolean
+ /**
+ * The variant that the condition's override serves. Null when the condition is not reachable, has no override, or its override names no variant of the flag.
+ * @nullable
+ */
+ pinned_variant: string | null
+}
+
+export interface ExperimentHealthInputsVariantApi {
+ /**
+ * The variant key. Null when the flag stores no string key.
+ * @nullable
+ */
+ key: string | null
+ /**
+ * The variant's share of the split, in percent. Null when the flag stores no number.
+ * @nullable
+ */
+ rollout_percentage: number | null
+}
+
+export interface ExperimentHealthInputsFlagApi {
+ /** Whether the flag is enabled. */
+ active: boolean
+ /** Whether the flag is deleted. */
+ deleted: boolean
+ /** The flag's release conditions, in evaluation order. */
+ release_conditions: ExperimentHealthInputsReleaseConditionApi[]
+ /** The flag's variants and their split. */
+ variants: ExperimentHealthInputsVariantApi[]
+}
+
+export interface ExperimentHealthInputsSplitChangeApi {
+ /** When the flag's split changed. */
+ changed_at: string
+ /** The split before the change. */
+ before: ExperimentHealthInputsVariantApi[]
+ /** The split after the change. */
+ after: ExperimentHealthInputsVariantApi[]
+ /** Whether the split-change check counts this change: it and every later change count from the first with an exposure before it, or an unknown answer. False for every change when not checked. */
+ counted: boolean
+}
+
+export interface ExperimentHealthInputsSplitHistoryApi {
+ /** Whether the split changes were compared with the exposures. False when not_checked_reason is set. */
+ checked: boolean
+ /**
+ * Why the split changes were not compared with the exposures: 'no_history_access', 'no_query_access', 'exposure_filters', 'exposure_action' or 'exposure_criteria'. Null when they were.
+ * @nullable
+ */
+ not_checked_reason: string | null
+ /** When the experiment launched. */
+ launched_at: string
+ /** The project's time zone, which the finding uses for times. */
+ team_timezone: string
+ /** Every split change since launch. Empty for 'no_history_access', which does not read them. */
+ changes: ExperimentHealthInputsSplitChangeApi[]
+ /**
+ * Whether anyone was exposed before the first counted change. Null when unknown or not checked.
+ * @nullable
+ */
+ exposed_before_first: boolean | null
+ /**
+ * Whether anyone was exposed between the first and the last change. Asked only when the last change restores the split from before the first. Null when not asked or unknown.
+ * @nullable
+ */
+ exposed_between: boolean | null
+}
+
+/**
+ * * `read` - Read
+ * * `not_needed` - Not Needed
+ * * `no_query_access` - No Query Access
+ * * `denied_properties` - Denied Properties
+ * * `no_flag_version` - No Flag Version
+ * * `unknown` - Unknown
+ */
+export type ExperimentHealthInputsTrafficStatusEnumApi =
+ (typeof ExperimentHealthInputsTrafficStatusEnumApi)[keyof typeof ExperimentHealthInputsTrafficStatusEnumApi]
+
+export const ExperimentHealthInputsTrafficStatusEnumApi = {
+ Read: 'read',
+ NotNeeded: 'not_needed',
+ NoQueryAccess: 'no_query_access',
+ DeniedProperties: 'denied_properties',
+ NoFlagVersion: 'no_flag_version',
+ Unknown: 'unknown',
+} as const
+
+export interface ExperimentHealthInputsConditionSetPeopleApi {
+ /** The number of the release condition, from 1. */
+ condition_set: number
+ /** The people whose latest call this condition served. */
+ people: number
+}
+
+export interface ExperimentHealthInputsConditionSetTrafficApi {
+ /** The start of the window: the latest of launch, the flag's last save and 7 days ago. */
+ since: string
+ /** The project's time zone, which the finding uses for times. */
+ team_timezone: string
+ /** People by the release condition that served their latest call of the flag's version. */
+ people_by_set: ExperimentHealthInputsConditionSetPeopleApi[]
+ /** The flag's calls in the window, of any flag version. */
+ calls: number
+ /** The calls that the flag service evaluated. Only those name a condition set. Local evaluation in a server SDK and a bootstrapped value name none. */
+ remotely_evaluated_calls: number
+}
+
+export interface ExperimentHealthInputsReaderAccessApi {
+ /** Whether the reader may read the flag's history, which the split-change check needs. */
+ can_read_flag_history: boolean
+ /** Whether the reader may query events, which the split-change and forced-variant checks need. */
+ can_query_events: boolean
+ /** Event properties the reader is denied. The forced-variant check skips its scan when one of them is a flag call property it reads. */
+ denied_event_properties: string[]
+}
+
+/**
+ * * `ready` - Ready
+ * * `stale` - Stale
+ * * `calculating` - Calculating
+ * * `not_launched` - Not Launched
+ * * `no_query_access` - No Query Access
+ * * `failed` - Failed
+ */
+export type HealthExposureInputsStatusEnumApi =
+ (typeof HealthExposureInputsStatusEnumApi)[keyof typeof HealthExposureInputsStatusEnumApi]
+
+export const HealthExposureInputsStatusEnumApi = {
+ Ready: 'ready',
+ Stale: 'stale',
+ Calculating: 'calculating',
+ NotLaunched: 'not_launched',
+ NoQueryAccess: 'no_query_access',
+ Failed: 'failed',
+} as const
+
+/**
+ * Exposed people by variant. '$multiple' counts the people exposed to more than one variant.
+ */
+export type ExperimentHealthInputsExposureTotalsApiTotalExposures = { [key: string]: number }
+
+export interface ExperimentHealthInputsExposureTotalsApi {
+ /** Exposed people by variant. '$multiple' counts the people exposed to more than one variant. */
+ total_exposures: ExperimentHealthInputsExposureTotalsApiTotalExposures
+ /** How the analysis treats people in several variants: 'exclude' or 'first_seen'. */
+ multiple_variant_handling: string
+ /**
+ * The p-value of the sample ratio test. Null when there was too little data.
+ * @nullable
+ */
+ sample_ratio_mismatch_p_value: number | null
+ /**
+ * Hours from launch to the computation of the answer, as the checks read them.
+ * @nullable
+ */
+ hours_since_launch: number | null
+}
+
+export interface ExperimentHealthInputsExposuresApi {
+ /** Whether a cached answer was read. 'calculating' means no answer is cached and a calculation runs in the background, so a later request reads a fresh answer. 'stale' means the cached answer is past its age: a recalculation runs in the background, or the last one failed and 'error' says why. After a failed calculation, no new one starts for 20 minutes.
+ *
+ * * `ready` - Ready
+ * * `stale` - Stale
+ * * `calculating` - Calculating
+ * * `not_launched` - Not Launched
+ * * `no_query_access` - No Query Access
+ * * `failed` - Failed */
+ status: HealthExposureInputsStatusEnumApi
+ /**
+ * When the answer was computed.
+ * @nullable
+ */
+ computed_at: string | null
+ /** What the exposure checks read. Null without an answer. */
+ totals: ExperimentHealthInputsExposureTotalsApi | null
+ /** The findings of the exposure checks on this answer: zero exposures, SRM and bias risk. */
+ findings: ExperimentHealthFindingApi[]
+ /**
+ * Why the query or its last background calculation failed. Set for 'failed', and for 'stale' when the recalculation failed.
+ * @nullable
+ */
+ error: string | null
+}
+
+/**
+ * * `ok` - Ok
+ * * `skipped` - Skipped
+ * * `timed_out` - Timed Out
+ * * `error` - Error
+ */
+export type SetupContextSectionStatusEnumApi =
+ (typeof SetupContextSectionStatusEnumApi)[keyof typeof SetupContextSectionStatusEnumApi]
+
+export const SetupContextSectionStatusEnumApi = {
+ Ok: 'ok',
+ Skipped: 'skipped',
+ TimedOut: 'timed_out',
+ Error: 'error',
+} as const
+
+export interface ExperimentSetupTeamDefaultsApi {
+ /**
+ * Default statistical method for new experiments: 'bayesian' or 'frequentist'.
+ * @nullable
+ */
+ stats_method: string | null
+ /**
+ * Default confidence level for new experiments, for example 0.95. Null when unset.
+ * @nullable
+ */
+ confidence_level: number | null
+ /**
+ * The team's default minimum detectable effect, as a percentage. Null when the team has not set one; product_default_minimum_detectable_effect applies then.
+ * @nullable
+ */
+ minimum_detectable_effect: number | null
+ /** The minimum detectable effect, as a percentage, that applies when the team has no default. */
+ product_default_minimum_detectable_effect: number
+ /** The statistical method that applies when the team has no default. */
+ product_default_stats_method: string
+ /** The confidence level that applies when the team has no default. Both methods use the same one. */
+ product_default_confidence_level: number
+ /** Default for counting only users whose metric window has fully passed. */
+ only_count_matured_users: boolean
+ /** Default for CUPED variance reduction on new experiments. */
+ cuped_enabled: boolean
+ /** Default for sequential testing. Applies only to the frequentist method. */
+ sequential_testing_enabled: boolean
+ /** Default for persisting flag values across authentication steps on new flags. It becomes the flag's ensure_experience_continuity. */
+ flags_persistence_default: boolean
+ /** How many filters the team uses to identify internal and test users. */
+ test_account_filter_count: number
+ /** A new experiment filters test accounts this way unless its own exposure criteria say otherwise. It does not follow the project's insight default. */
+ new_experiments_filter_test_accounts: boolean
+ /** The exposure event a new experiment launched now counts by default: '$experiment_exposure' or '$feature_flag_called'. */
+ default_exposure_event: string
+}
+
+export interface ExperimentSetupTeamDefaultsSectionApi {
+ /** 'ok' when data holds the section. 'skipped' when an input the section needs was not passed. 'timed_out' when the query was too expensive to finish. 'error' when the read failed. Every status other than 'ok' leaves data null, and the other sections are still valid.
+ *
+ * * `ok` - Ok
+ * * `skipped` - Skipped
+ * * `timed_out` - Timed Out
+ * * `error` - Error */
+ status: SetupContextSectionStatusEnumApi
+ /** The team's experiment defaults. */
+ data: ExperimentSetupTeamDefaultsApi | null
+}
+
+/**
+ * * `web` - Web
+ * * `mobile` - Mobile
+ * * `server` - Server
+ * * `other` - Other
+ */
+export type SdkLibCategoryEnumApi = (typeof SdkLibCategoryEnumApi)[keyof typeof SdkLibCategoryEnumApi]
+
+export const SdkLibCategoryEnumApi = {
+ Web: 'web',
+ Mobile: 'mobile',
+ Server: 'server',
+ Other: 'other',
+} as const
+
+export interface ExperimentSetupSdkLibApi {
+ /**
+ * The $lib value of the SDK, for example 'web'.
+ * @nullable
+ */
+ lib: string | null
+ /** 'web' for the JavaScript web SDK, 'mobile', 'server', or 'other' for libraries not classified.
+ *
+ * * `web` - Web
+ * * `mobile` - Mobile
+ * * `server` - Server
+ * * `other` - Other */
+ category: SdkLibCategoryEnumApi
+ /** Multivariate flag calls this SDK sent in the window. */
+ calls: number
+ /** Distinct ids that sent those calls. */
+ distinct_ids: number
+ /** Share of calls that carry a $device_id. 0 when this SDK never sends one, as server SDKs don't. */
+ device_id_share: number
+ /**
+ * Share of calls evaluated locally in the SDK instead of by the flags service. Null when no call from this SDK reported it, as the web SDK doesn't.
+ * @nullable
+ */
+ locally_evaluated_share: number | null
+ /**
+ * Share of distinct ids that were anonymous, among those that report whether they are identified. Null when no call from this SDK reported it.
+ * @nullable
+ */
+ anonymous_share: number | null
+}
+
+export interface ExperimentSetupLibActivityApi {
+ /**
+ * The $lib value of the SDK, for example 'web'.
+ * @nullable
+ */
+ lib: string | null
+ /** 'web', 'mobile', 'server', or 'other'.
+ *
+ * * `web` - Web
+ * * `mobile` - Mobile
+ * * `server` - Server
+ * * `other` - Other */
+ category: SdkLibCategoryEnumApi
+ /** Events this SDK sent in the window, of any kind. */
+ events: number
+ /** Distinct ids that sent those events. */
+ distinct_ids: number
+}
+
+export interface ExperimentSetupSdkProfileApi {
+ /** Days of flag calls read, ending now. */
+ window_days: number
+ /** The event read: '$experiment_exposure' when the project receives it, otherwise '$feature_flag_called'. Only one is read, because one copies the other, and only multivariate responses count either way. This says what the project's events carry today, so it can differ from team_defaults.default_exposure_event, which says what a new experiment would count. */
+ source_event: string
+ /** When the numbers were computed. They are cached for hours. */
+ computed_at: string
+ /** One row per SDK, most calls first. */
+ libs: ExperimentSetupSdkLibApi[]
+ /** True when more SDKs sent flag calls than libs lists. */
+ libs_truncated: boolean
+ /** Distinct multivariate flag keys called in the window. */
+ flags_seen: number
+ /** How many of those flag keys were called by both a server SDK and the web SDK. */
+ flags_evaluated_on_server_and_web: number
+ /** True when at least one flag key was called by both a server SDK and the web SDK. The same flag decided on the server and read in the browser can bucket one user into two variants. */
+ evaluated_on_server_and_web: boolean
+ /**
+ * Up to 10 SDKs seen on any event over the last day, most events first. Set only when libs is empty, so a project creating its first experiment still says which platforms it sends from. Null when flag calls exist, and null when this extra read timed out.
+ * @nullable
+ */
+ libs_on_any_event: ExperimentSetupLibActivityApi[] | null
+ /** True when more SDKs sent events than libs_on_any_event lists. False when it is null. */
+ libs_on_any_event_truncated: boolean
+}
+
+export interface ExperimentSetupSdkProfileSectionApi {
+ /** 'ok' when data holds the section. 'skipped' when an input the section needs was not passed. 'timed_out' when the query was too expensive to finish. 'error' when the read failed. Every status other than 'ok' leaves data null, and the other sections are still valid.
+ *
+ * * `ok` - Ok
+ * * `skipped` - Skipped
+ * * `timed_out` - Timed Out
+ * * `error` - Error */
+ status: SetupContextSectionStatusEnumApi
+ /** Which SDKs send multivariate flag calls, across the whole project. */
+ data: ExperimentSetupSdkProfileApi | null
+}
+
+export interface ExperimentHealthInputsProjectApi {
+ /** The project's experiment defaults. */
+ team_defaults: ExperimentSetupTeamDefaultsSectionApi
+ /** Which SDKs call feature flags and where flags are evaluated, across the whole project. Skipped for a reader who may not query events. */
+ sdk_profile: ExperimentSetupSdkProfileSectionApi
+}
+
+export interface ExperimentHealthInputsApi {
+ /** Whether the experiment has a start date. */
+ is_launched: boolean
+ /** Whether the experiment is launched and not ended. */
+ is_running: boolean
+ /** Whether the experiment has an end date. */
+ has_ended: boolean
+ /** Whether the experiment is paused. */
+ is_paused: boolean
+ /** Whether the experiment is archived. */
+ archived: boolean
+ /**
+ * The baseline set in the experiment's settings. Null when unset.
+ * @nullable
+ */
+ baseline_variant_key: string | null
+ /** The variants the analysis leaves out of the results. The forced-variant check ignores pins to them. */
+ excluded_variant_keys: string[]
+ /** Single-use primary metrics plus shared metrics linked as primary. */
+ primary_metric_count: number
+ /** Single-use secondary metrics plus shared metrics linked as secondary. */
+ secondary_metric_count: number
+ /** The experiment's feature flag. Null when it has none. */
+ flag: ExperimentHealthInputsFlagApi | null
+ /** The changes of the flag's split since launch. Null when the experiment is not running, is archived, its flag is missing or deleted, or the read failed. */
+ split_history: ExperimentHealthInputsSplitHistoryApi | null
+ /** Whether the condition-set traffic was read, or why not. The forced-variant check needs it when the experiment is launched and some but not all release conditions pin a variant that has a share of the split and is not excluded from the analysis.
+ *
+ * * `read` - Read
+ * * `not_needed` - Not Needed
+ * * `no_query_access` - No Query Access
+ * * `denied_properties` - Denied Properties
+ * * `no_flag_version` - No Flag Version
+ * * `unknown` - Unknown */
+ condition_set_traffic_status: ExperimentHealthInputsTrafficStatusEnumApi
+ /** The flag's recent calls by condition set. Null unless condition_set_traffic_status is 'read'. */
+ condition_set_traffic: ExperimentHealthInputsConditionSetTrafficApi | null
+ /** What the reader may read, which decides what the checks can load. */
+ reader_access: ExperimentHealthInputsReaderAccessApi
+ /** The exposure query's answer that the exposure checks read, from the cache. */
+ exposures: ExperimentHealthInputsExposuresApi
+ /** Facts about the project that no check reads yet, from the same providers as the setup context. */
+ project: ExperimentHealthInputsProjectApi
+}
+
/**
* How the recordings tab's in-session exposure scope reads on this experiment.
*/
@@ -3978,175 +4399,6 @@ export interface ExperimentSetupContextInputApi {
shared_metrics_limit?: number
}
-/**
- * * `ok` - Ok
- * * `skipped` - Skipped
- * * `timed_out` - Timed Out
- * * `error` - Error
- */
-export type SetupContextSectionStatusEnumApi =
- (typeof SetupContextSectionStatusEnumApi)[keyof typeof SetupContextSectionStatusEnumApi]
-
-export const SetupContextSectionStatusEnumApi = {
- Ok: 'ok',
- Skipped: 'skipped',
- TimedOut: 'timed_out',
- Error: 'error',
-} as const
-
-export interface ExperimentSetupTeamDefaultsApi {
- /**
- * Default statistical method for new experiments: 'bayesian' or 'frequentist'.
- * @nullable
- */
- stats_method: string | null
- /**
- * Default confidence level for new experiments, for example 0.95. Null when unset.
- * @nullable
- */
- confidence_level: number | null
- /**
- * The team's default minimum detectable effect, as a percentage. Null when the team has not set one; product_default_minimum_detectable_effect applies then.
- * @nullable
- */
- minimum_detectable_effect: number | null
- /** The minimum detectable effect, as a percentage, that applies when the team has no default. */
- product_default_minimum_detectable_effect: number
- /** The statistical method that applies when the team has no default. */
- product_default_stats_method: string
- /** The confidence level that applies when the team has no default. Both methods use the same one. */
- product_default_confidence_level: number
- /** Default for counting only users whose metric window has fully passed. */
- only_count_matured_users: boolean
- /** Default for CUPED variance reduction on new experiments. */
- cuped_enabled: boolean
- /** Default for sequential testing. Applies only to the frequentist method. */
- sequential_testing_enabled: boolean
- /** Default for persisting flag values across authentication steps on new flags. It becomes the flag's ensure_experience_continuity. */
- flags_persistence_default: boolean
- /** How many filters the team uses to identify internal and test users. */
- test_account_filter_count: number
- /** A new experiment filters test accounts this way unless its own exposure criteria say otherwise. It does not follow the project's insight default. */
- new_experiments_filter_test_accounts: boolean
- /** The exposure event a new experiment launched now counts by default: '$experiment_exposure' or '$feature_flag_called'. */
- default_exposure_event: string
-}
-
-export interface ExperimentSetupTeamDefaultsSectionApi {
- /** 'ok' when data holds the section. 'skipped' when an input the section needs was not passed. 'timed_out' when the query was too expensive to finish. 'error' when the read failed. Every status other than 'ok' leaves data null, and the other sections are still valid.
- *
- * * `ok` - Ok
- * * `skipped` - Skipped
- * * `timed_out` - Timed Out
- * * `error` - Error */
- status: SetupContextSectionStatusEnumApi
- /** The team's experiment defaults. */
- data: ExperimentSetupTeamDefaultsApi | null
-}
-
-/**
- * * `web` - Web
- * * `mobile` - Mobile
- * * `server` - Server
- * * `other` - Other
- */
-export type SdkLibCategoryEnumApi = (typeof SdkLibCategoryEnumApi)[keyof typeof SdkLibCategoryEnumApi]
-
-export const SdkLibCategoryEnumApi = {
- Web: 'web',
- Mobile: 'mobile',
- Server: 'server',
- Other: 'other',
-} as const
-
-export interface ExperimentSetupSdkLibApi {
- /**
- * The $lib value of the SDK, for example 'web'.
- * @nullable
- */
- lib: string | null
- /** 'web' for the JavaScript web SDK, 'mobile', 'server', or 'other' for libraries not classified.
- *
- * * `web` - Web
- * * `mobile` - Mobile
- * * `server` - Server
- * * `other` - Other */
- category: SdkLibCategoryEnumApi
- /** Multivariate flag calls this SDK sent in the window. */
- calls: number
- /** Distinct ids that sent those calls. */
- distinct_ids: number
- /** Share of calls that carry a $device_id. 0 when this SDK never sends one, as server SDKs don't. */
- device_id_share: number
- /**
- * Share of calls evaluated locally in the SDK instead of by the flags service. Null when no call from this SDK reported it, as the web SDK doesn't.
- * @nullable
- */
- locally_evaluated_share: number | null
- /**
- * Share of distinct ids that were anonymous, among those that report whether they are identified. Null when no call from this SDK reported it.
- * @nullable
- */
- anonymous_share: number | null
-}
-
-export interface ExperimentSetupLibActivityApi {
- /**
- * The $lib value of the SDK, for example 'web'.
- * @nullable
- */
- lib: string | null
- /** 'web', 'mobile', 'server', or 'other'.
- *
- * * `web` - Web
- * * `mobile` - Mobile
- * * `server` - Server
- * * `other` - Other */
- category: SdkLibCategoryEnumApi
- /** Events this SDK sent in the window, of any kind. */
- events: number
- /** Distinct ids that sent those events. */
- distinct_ids: number
-}
-
-export interface ExperimentSetupSdkProfileApi {
- /** Days of flag calls read, ending now. */
- window_days: number
- /** The event read: '$experiment_exposure' when the project receives it, otherwise '$feature_flag_called'. Only one is read, because one copies the other, and only multivariate responses count either way. This says what the project's events carry today, so it can differ from team_defaults.default_exposure_event, which says what a new experiment would count. */
- source_event: string
- /** When the numbers were computed. They are cached for hours. */
- computed_at: string
- /** One row per SDK, most calls first. */
- libs: ExperimentSetupSdkLibApi[]
- /** True when more SDKs sent flag calls than libs lists. */
- libs_truncated: boolean
- /** Distinct multivariate flag keys called in the window. */
- flags_seen: number
- /** How many of those flag keys were called by both a server SDK and the web SDK. */
- flags_evaluated_on_server_and_web: number
- /** True when at least one flag key was called by both a server SDK and the web SDK. The same flag decided on the server and read in the browser can bucket one user into two variants. */
- evaluated_on_server_and_web: boolean
- /**
- * Up to 10 SDKs seen on any event over the last day, most events first. Set only when libs is empty, so a project creating its first experiment still says which platforms it sends from. Null when flag calls exist, and null when this extra read timed out.
- * @nullable
- */
- libs_on_any_event: ExperimentSetupLibActivityApi[] | null
- /** True when more SDKs sent events than libs_on_any_event lists. False when it is null. */
- libs_on_any_event_truncated: boolean
-}
-
-export interface ExperimentSetupSdkProfileSectionApi {
- /** 'ok' when data holds the section. 'skipped' when an input the section needs was not passed. 'timed_out' when the query was too expensive to finish. 'error' when the read failed. Every status other than 'ok' leaves data null, and the other sections are still valid.
- *
- * * `ok` - Ok
- * * `skipped` - Skipped
- * * `timed_out` - Timed Out
- * * `error` - Error */
- status: SetupContextSectionStatusEnumApi
- /** Which SDKs send multivariate flag calls, across the whole project. */
- data: ExperimentSetupSdkProfileApi | null
-}
-
export interface ExperimentSetupLibReachApi {
/**
* The $lib value that sent the target events.
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index 9a71247b01d4..d8d6f1addd09 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -20,6 +20,7 @@ import type {
ExperimentFlagCleanupTargetApi,
ExperimentFlagCleanupTaskApi,
ExperimentHealthApi,
+ ExperimentHealthInputsApi,
ExperimentHoldoutApi,
ExperimentHoldoutsListParams,
ExperimentInSessionExposureApi,
@@ -734,6 +735,28 @@ export const experimentsHealthRetrieve = async (
})
}
+export const getExperimentsHealthInputsRetrieveUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/experiments/${id}/health_inputs/`
+}
+
+/**
+ * Staff only. The inputs that the health checks read for this reader, to debug why a finding shows or not:
+ * the context of the checks in `health`, the exposure query's answer that the exposure checks read, and facts
+ * about the project from the setup context's providers (the team's experiment defaults and which SDKs call
+ * flags). The exposure answer comes from the cache. When it is missing or stale, a calculation starts in the
+ * background and `exposures.status` says so.
+ */
+export const experimentsHealthInputsRetrieve = async (
+ projectId: string,
+ id: number,
+ options?: RequestInit
+): Promise<ExperimentHealthInputsApi> => {
+ return apiMutator<ExperimentHealthInputsApi>(getExperimentsHealthInputsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getExperimentsInSessionExposureRetrieveUrl = (projectId: string, id: number) => {
return `/api/projects/${projectId}/experiments/${id}/in_session_exposure/`
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b794907562e7..74effa84e3c1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -45060,6 +45060,428 @@ export namespace Schemas {
can_view_task: boolean;
}
+ export interface ExperimentHealthInputsReleaseCondition {
+ /** The condition's position in the flag, from 1, as the flag page labels it ('Set 2'). */
+ number: number;
+ /**
+ * The condition's rollout, in percent. Null when the flag stores no number.
+ * @nullable
+ */
+ rollout_percentage: number | null;
+ /**
+ * The number of property filters. Null when the flag stores no list.
+ * @nullable
+ */
+ property_count: number | null;
+ /** Whether the condition can serve a request. A condition after one that matches everyone never does. */
+ reachable: boolean;
+ /**
+ * The variant that the condition's override serves. Null when the condition is not reachable, has no override, or its override names no variant of the flag.
+ * @nullable
+ */
+ pinned_variant: string | null;
+ }
+
+ export interface ExperimentHealthInputsVariant {
+ /**
+ * The variant key. Null when the flag stores no string key.
+ * @nullable
+ */
+ key: string | null;
+ /**
+ * The variant's share of the split, in percent. Null when the flag stores no number.
+ * @nullable
+ */
+ rollout_percentage: number | null;
+ }
+
+ export interface ExperimentHealthInputsFlag {
+ /** Whether the flag is enabled. */
+ active: boolean;
+ /** Whether the flag is deleted. */
+ deleted: boolean;
+ /** The flag's release conditions, in evaluation order. */
+ release_conditions: ExperimentHealthInputsReleaseCondition[];
+ /** The flag's variants and their split. */
+ variants: ExperimentHealthInputsVariant[];
+ }
+
+ export interface ExperimentHealthInputsSplitChange {
+ /** When the flag's split changed. */
+ changed_at: string;
+ /** The split before the change. */
+ before: ExperimentHealthInputsVariant[];
+ /** The split after the change. */
+ after: ExperimentHealthInputsVariant[];
+ /** Whether the split-change check counts this change: it and every later change count from the first with an exposure before it, or an unknown answer. False for every change when not checked. */
+ counted: boolean;
+ }
+
+ export interface ExperimentHealthInputsSplitHistory {
+ /** Whether the split changes were compared with the exposures. False when not_checked_reason is set. */
+ checked: boolean;
+ /**
+ * Why the split changes were not compared with the exposures: 'no_history_access', 'no_query_access', 'exposure_filters', 'exposure_action' or 'exposure_criteria'. Null when they were.
+ * @nullable
+ */
+ not_checked_reason: string | null;
+ /** When the experiment launched. */
+ launched_at: string;
+ /** The project's time zone, which the finding uses for times. */
+ team_timezone: string;
+ /** Every split change since launch. Empty for 'no_history_access', which does not read them. */
+ changes: ExperimentHealthInputsSplitChange[];
+ /**
+ * Whether anyone was exposed before the first counted change. Null when unknown or not checked.
+ * @nullable
+ */
+ exposed_before_first: boolean | null;
+ /**
+ * Whether anyone was exposed between the first and the last change. Asked only when the last change restores the split from before the first. Null when not asked or unknown.
+ * @nullable
+ */
+ exposed_between: boolean | null;
+ }
+
+ /**
+ * * `read` - Read
+ * * `not_needed` - Not Needed
+ * * `no_query_access` - No Query Access
+ * * `denied_properties` - Denied Properties
+ * * `no_flag_version` - No Flag Version
+ * * `unknown` - Unknown
+ */
+ export type ExperimentHealthInputsTrafficStatusEnum = typeof ExperimentHealthInputsTrafficStatusEnum[keyof typeof ExperimentHealthInputsTrafficStatusEnum];
+
+
+ export const ExperimentHealthInputsTrafficStatusEnum = {
+ Read: 'read',
+ NotNeeded: 'not_needed',
+ NoQueryAccess: 'no_query_access',
+ DeniedProperties: 'denied_properties',
+ NoFlagVersion: 'no_flag_version',
+ Unknown: 'unknown',
+ } as const;
+
+ export interface ExperimentHealthInputsConditionSetPeople {
+ /** The number of the release condition, from 1. */
+ condition_set: number;
+ /** The people whose latest call this condition served. */
+ people: number;
+ }
+
+ export interface ExperimentHealthInputsConditionSetTraffic {
+ /** The start of the window: the latest of launch, the flag's last save and 7 days ago. */
+ since: string;
+ /** The project's time zone, which the finding uses for times. */
+ team_timezone: string;
+ /** People by the release condition that served their latest call of the flag's version. */
+ people_by_set: ExperimentHealthInputsConditionSetPeople[];
+ /** The flag's calls in the window, of any flag version. */
+ calls: number;
+ /** The calls that the flag service evaluated. Only those name a condition set. Local evaluation in a server SDK and a bootstrapped value name none. */
+ remotely_evaluated_calls: number;
+ }
+
+ export interface ExperimentHealthInputsReaderAccess {
+ /** Whether the reader may read the flag's history, which the split-change check needs. */
+ can_read_flag_history: boolean;
+ /** Whether the reader may query events, which the split-change and forced-variant checks need. */
+ can_query_events: boolean;
+ /** Event properties the reader is denied. The forced-variant check skips its scan when one of them is a flag call property it reads. */
+ denied_event_properties: string[];
+ }
+
+ /**
+ * * `ready` - Ready
+ * * `stale` - Stale
+ * * `calculating` - Calculating
+ * * `not_launched` - Not Launched
+ * * `no_query_access` - No Query Access
+ * * `failed` - Failed
+ */
+ export type HealthExposureInputsStatusEnum = typeof HealthExposureInputsStatusEnum[keyof typeof HealthExposureInputsStatusEnum];
+
+
+ export const HealthExposureInputsStatusEnum = {
+ Ready: 'ready',
+ Stale: 'stale',
+ Calculating: 'calculating',
+ NotLaunched: 'not_launched',
+ NoQueryAccess: 'no_query_access',
+ Failed: 'failed',
+ } as const;
+
+ /**
+ * Exposed people by variant. '$multiple' counts the people exposed to more than one variant.
+ */
+ export type ExperimentHealthInputsExposureTotalsTotalExposures = {[key: string]: number};
+
+ export interface ExperimentHealthInputsExposureTotals {
+ /** Exposed people by variant. '$multiple' counts the people exposed to more than one variant. */
+ total_exposures: ExperimentHealthInputsExposureTotalsTotalExposures;
+ /** How the analysis treats people in several variants: 'exclude' or 'first_seen'. */
+ multiple_variant_handling: string;
+ /**
+ * The p-value of the sample ratio test. Null when there was too little data.
+ * @nullable
+ */
+ sample_ratio_mismatch_p_value: number | null;
+ /**
+ * Hours from launch to the computation of the answer, as the checks read them.
+ * @nullable
+ */
+ hours_since_launch: number | null;
+ }
+
+ export interface ExperimentHealthInputsExposures {
+ /** Whether a cached answer was read. 'calculating' means no answer is cached and a calculation runs in the background, so a later request reads a fresh answer. 'stale' means the cached answer is past its age: a recalculation runs in the background, or the last one failed and 'error' says why. After a failed calculation, no new one starts for 20 minutes.
+ *
+ * * `ready` - Ready
+ * * `stale` - Stale
+ * * `calculating` - Calculating
+ * * `not_launched` - Not Launched
+ * * `no_query_access` - No Query Access
+ * * `failed` - Failed */
+ status: HealthExposureInputsStatusEnum;
+ /**
+ * When the answer was computed.
+ * @nullable
+ */
+ computed_at: string | null;
+ /** What the exposure checks read. Null without an answer. */
+ totals: ExperimentHealthInputsExposureTotals | null;
+ /** The findings of the exposure checks on this answer: zero exposures, SRM and bias risk. */
+ findings: ExperimentHealthFinding[];
+ /**
+ * Why the query or its last background calculation failed. Set for 'failed', and for 'stale' when the recalculation failed.
+ * @nullable
+ */
+ error: string | null;
+ }
+
+ /**
+ * * `ok` - Ok
+ * * `skipped` - Skipped
+ * * `timed_out` - Timed Out
+ * * `error` - Error
+ */
+ export type SetupContextSectionStatusEnum = typeof SetupContextSectionStatusEnum[keyof typeof SetupContextSectionStatusEnum];
+
+
+ export const SetupContextSectionStatusEnum = {
+ Ok: 'ok',
+ Skipped: 'skipped',
+ TimedOut: 'timed_out',
+ Error: 'error',
+ } as const;
+
+ export interface ExperimentSetupTeamDefaults {
+ /**
+ * Default statistical method for new experiments: 'bayesian' or 'frequentist'.
+ * @nullable
+ */
+ stats_method: string | null;
+ /**
+ * Default confidence level for new experiments, for example 0.95. Null when unset.
+ * @nullable
+ */
+ confidence_level: number | null;
+ /**
+ * The team's default minimum detectable effect, as a percentage. Null when the team has not set one; product_default_minimum_detectable_effect applies then.
+ * @nullable
+ */
+ minimum_detectable_effect: number | null;
+ /** The minimum detectable effect, as a percentage, that applies when the team has no default. */
+ product_default_minimum_detectable_effect: number;
+ /** The statistical method that applies when the team has no default. */
+ product_default_stats_method: string;
+ /** The confidence level that applies when the team has no default. Both methods use the same one. */
+ product_default_confidence_level: number;
+ /** Default for counting only users whose metric window has fully passed. */
+ only_count_matured_users: boolean;
+ /** Default for CUPED variance reduction on new experiments. */
+ cuped_enabled: boolean;
+ /** Default for sequential testing. Applies only to the frequentist method. */
+ sequential_testing_enabled: boolean;
+ /** Default for persisting flag values across authentication steps on new flags. It becomes the flag's ensure_experience_continuity. */
+ flags_persistence_default: boolean;
+ /** How many filters the team uses to identify internal and test users. */
+ test_account_filter_count: number;
+ /** A new experiment filters test accounts this way unless its own exposure criteria say otherwise. It does not follow the project's insight default. */
+ new_experiments_filter_test_accounts: boolean;
+ /** The exposure event a new experiment launched now counts by default: '$experiment_exposure' or '$feature_flag_called'. */
+ default_exposure_event: string;
+ }
+
+ export interface ExperimentSetupTeamDefaultsSection {
+ /** 'ok' when data holds the section. 'skipped' when an input the section needs was not passed. 'timed_out' when the query was too expensive to finish. 'error' when the read failed. Every status other than 'ok' leaves data null, and the other sections are still valid.
+ *
+ * * `ok` - Ok
+ * * `skipped` - Skipped
+ * * `timed_out` - Timed Out
+ * * `error` - Error */
+ status: SetupContextSectionStatusEnum;
+ /** The team's experiment defaults. */
+ data: ExperimentSetupTeamDefaults | null;
+ }
+
+ /**
+ * * `web` - Web
+ * * `mobile` - Mobile
+ * * `server` - Server
+ * * `other` - Other
+ */
+ export type SdkLibCategoryEnum = typeof SdkLibCategoryEnum[keyof typeof SdkLibCategoryEnum];
+
+
+ export const SdkLibCategoryEnum = {
+ Web: 'web',
+ Mobile: 'mobile',
+ Server: 'server',
+ Other: 'other',
+ } as const;
+
+ export interface ExperimentSetupSdkLib {
+ /**
+ * The $lib value of the SDK, for example 'web'.
+ * @nullable
+ */
+ lib: string | null;
+ /** 'web' for the JavaScript web SDK, 'mobile', 'server', or 'other' for libraries not classified.
+ *
+ * * `web` - Web
+ * * `mobile` - Mobile
+ * * `server` - Server
+ * * `other` - Other */
+ category: SdkLibCategoryEnum;
+ /** Multivariate flag calls this SDK sent in the window. */
+ calls: number;
+ /** Distinct ids that sent those calls. */
+ distinct_ids: number;
+ /** Share of calls that carry a $device_id. 0 when this SDK never sends one, as server SDKs don't. */
+ device_id_share: number;
+ /**
+ * Share of calls evaluated locally in the SDK instead of by the flags service. Null when no call from this SDK reported it, as the web SDK doesn't.
+ * @nullable
+ */
+ locally_evaluated_share: number | null;
+ /**
+ * Share of distinct ids that were anonymous, among those that report whether they are identified. Null when no call from this SDK reported it.
+ * @nullable
+ */
+ anonymous_share: number | null;
+ }
+
+ export interface ExperimentSetupLibActivity {
+ /**
+ * The $lib value of the SDK, for example 'web'.
+ * @nullable
+ */
+ lib: string | null;
+ /** 'web', 'mobile', 'server', or 'other'.
+ *
+ * * `web` - Web
+ * * `mobile` - Mobile
+ * * `server` - Server
+ * * `other` - Other */
+ category: SdkLibCategoryEnum;
+ /** Events this SDK sent in the window, of any kind. */
+ events: number;
+ /** Distinct ids that sent those events. */
+ distinct_ids: number;
+ }
+
+ export interface ExperimentSetupSdkProfile {
+ /** Days of flag calls read, ending now. */
+ window_days: number;
+ /** The event read: '$experiment_exposure' when the project receives it, otherwise '$feature_flag_called'. Only one is read, because one copies the other, and only multivariate responses count either way. This says what the project's events carry today, so it can differ from team_defaults.default_exposure_event, which says what a new experiment would count. */
+ source_event: string;
+ /** When the numbers were computed. They are cached for hours. */
+ computed_at: string;
+ /** One row per SDK, most calls first. */
+ libs: ExperimentSetupSdkLib[];
+ /** True when more SDKs sent flag calls than libs lists. */
+ libs_truncated: boolean;
+ /** Distinct multivariate flag keys called in the window. */
+ flags_seen: number;
+ /** How many of those flag keys were called by both a server SDK and the web SDK. */
+ flags_evaluated_on_server_and_web: number;
+ /** True when at least one flag key was called by both a server SDK and the web SDK. The same flag decided on the server and read in the browser can bucket one user into two variants. */
+ evaluated_on_server_and_web: boolean;
+ /**
+ * Up to 10 SDKs seen on any event over the last day, most events first. Set only when libs is empty, so a project creating its first experiment still says which platforms it sends from. Null when flag calls exist, and null when this extra read timed out.
+ * @nullable
+ */
+ libs_on_any_event: ExperimentSetupLibActivity[] | null;
+ /** True when more SDKs sent events than libs_on_any_event lists. False when it is null. */
+ libs_on_any_event_truncated: boolean;
+ }
+
+ export interface ExperimentSetupSdkProfileSection {
+ /** 'ok' when data holds the section. 'skipped' when an input the section needs was not passed. 'timed_out' when the query was too expensive to finish. 'error' when the read failed. Every status other than 'ok' leaves data null, and the other sections are still valid.
+ *
+ * * `ok` - Ok
+ * * `skipped` - Skipped
+ * * `timed_out` - Timed Out
+ * * `error` - Error */
+ status: SetupContextSectionStatusEnum;
+ /** Which SDKs send multivariate flag calls, across the whole project. */
+ data: ExperimentSetupSdkProfile | null;
+ }
+
+ export interface ExperimentHealthInputsProject {
+ /** The project's experiment defaults. */
+ team_defaults: ExperimentSetupTeamDefaultsSection;
+ /** Which SDKs call feature flags and where flags are evaluated, across the whole project. Skipped for a reader who may not query events. */
+ sdk_profile: ExperimentSetupSdkProfileSection;
+ }
+
+ export interface ExperimentHealthInputs {
+ /** Whether the experiment has a start date. */
+ is_launched: boolean;
+ /** Whether the experiment is launched and not ended. */
+ is_running: boolean;
+ /** Whether the experiment has an end date. */
+ has_ended: boolean;
+ /** Whether the experiment is paused. */
+ is_paused: boolean;
+ /** Whether the experiment is archived. */
+ archived: boolean;
+ /**
+ * The baseline set in the experiment's settings. Null when unset.
+ * @nullable
+ */
+ baseline_variant_key: string | null;
+ /** The variants the analysis leaves out of the results. The forced-variant check ignores pins to them. */
+ excluded_variant_keys: string[];
+ /** Single-use primary metrics plus shared metrics linked as primary. */
+ primary_metric_count: number;
+ /** Single-use secondary metrics plus shared metrics linked as secondary. */
+ secondary_metric_count: number;
+ /** The experiment's feature flag. Null when it has none. */
+ flag: ExperimentHealthInputsFlag | null;
+ /** The changes of the flag's split since launch. Null when the experiment is not running, is archived, its flag is missing or deleted, or the read failed. */
+ split_history: ExperimentHealthInputsSplitHistory | null;
+ /** Whether the condition-set traffic was read, or why not. The forced-variant check needs it when the experiment is launched and some but not all release conditions pin a variant that has a share of the split and is not excluded from the analysis.
+ *
+ * * `read` - Read
+ * * `not_needed` - Not Needed
+ * * `no_query_access` - No Query Access
+ * * `denied_properties` - Denied Properties
+ * * `no_flag_version` - No Flag Version
+ * * `unknown` - Unknown */
+ condition_set_traffic_status: ExperimentHealthInputsTrafficStatusEnum;
+ /** The flag's recent calls by condition set. Null unless condition_set_traffic_status is 'read'. */
+ condition_set_traffic: ExperimentHealthInputsConditionSetTraffic | null;
+ /** What the reader may read, which decides what the checks can load. */
+ reader_access: ExperimentHealthInputsReaderAccess;
+ /** The exposure query's answer that the exposure checks read, from the cache. */
+ exposures: ExperimentHealthInputsExposures;
+ /** Facts about the project that no check reads yet, from the same providers as the setup context. */
+ project: ExperimentHealthInputsProject;
+ }
+
/**
* How the recordings tab's in-session exposure scope reads on this experiment.
*/
@@ -45917,22 +46339,6 @@ export namespace Schemas {
unique_persons: number | null;
}
- /**
- * * `ok` - Ok
- * * `skipped` - Skipped
- * * `timed_out` - Timed Out
- * * `error` - Error
- */
- export type SetupContextSectionStatusEnum = typeof SetupContextSectionStatusEnum[keyof typeof SetupContextSectionStatusEnum];
-
-
- export const SetupContextSectionStatusEnum = {
- Ok: 'ok',
- Skipped: 'skipped',
- TimedOut: 'timed_out',
- Error: 'error',
- } as const;
-
export interface ExperimentSetupCandidateMetricSection {
/** 'ok' when data holds the section. 'skipped' when an input the section needs was not passed. 'timed_out' when the query was too expensive to finish. 'error' when the read failed. Every status other than 'ok' leaves data null, and the other sections are still valid.
*
@@ -45986,160 +46392,6 @@ export namespace Schemas {
shared_metrics_limit?: number;
}
- export interface ExperimentSetupTeamDefaults {
- /**
- * Default statistical method for new experiments: 'bayesian' or 'frequentist'.
- * @nullable
- */
- stats_method: string | null;
- /**
- * Default confidence level for new experiments, for example 0.95. Null when unset.
- * @nullable
- */
- confidence_level: number | null;
- /**
- * The team's default minimum detectable effect, as a percentage. Null when the team has not set one; product_default_minimum_detectable_effect applies then.
- * @nullable
- */
- minimum_detectable_effect: number | null;
- /** The minimum detectable effect, as a percentage, that applies when the team has no default. */
- product_default_minimum_detectable_effect: number;
- /** The statistical method that applies when the team has no default. */
- product_default_stats_method: string;
- /** The confidence level that applies when the team has no default. Both methods use the same one. */
- product_default_confidence_level: number;
- /** Default for counting only users whose metric window has fully passed. */
- only_count_matured_users: boolean;
- /** Default for CUPED variance reduction on new experiments. */
- cuped_enabled: boolean;
- /** Default for sequential testing. Applies only to the frequentist method. */
- sequential_testing_enabled: boolean;
- /** Default for persisting flag values across authentication steps on new flags. It becomes the flag's ensure_experience_continuity. */
- flags_persistence_default: boolean;
- /** How many filters the team uses to identify internal and test users. */
- test_account_filter_count: number;
- /** A new experiment filters test accounts this way unless its own exposure criteria say otherwise. It does not follow the project's insight default. */
- new_experiments_filter_test_accounts: boolean;
- /** The exposure event a new experiment launched now counts by default: '$experiment_exposure' or '$feature_flag_called'. */
- default_exposure_event: string;
- }
-
- export interface ExperimentSetupTeamDefaultsSection {
- /** 'ok' when data holds the section. 'skipped' when an input the section needs was not passed. 'timed_out' when the query was too expensive to finish. 'error' when the read failed. Every status other than 'ok' leaves data null, and the other sections are still valid.
- *
- * * `ok` - Ok
- * * `skipped` - Skipped
- * * `timed_out` - Timed Out
- * * `error` - Error */
- status: SetupContextSectionStatusEnum;
- /** The team's experiment defaults. */
- data: ExperimentSetupTeamDefaults | null;
- }
-
- /**
- * * `web` - Web
- * * `mobile` - Mobile
- * * `server` - Server
- * * `other` - Other
- */
- export type SdkLibCategoryEnum = typeof SdkLibCategoryEnum[keyof typeof SdkLibCategoryEnum];
-
-
- export const SdkLibCategoryEnum = {
- Web: 'web',
- Mobile: 'mobile',
- Server: 'server',
- Other: 'other',
- } as const;
-
- export interface ExperimentSetupSdkLib {
- /**
- * The $lib value of the SDK, for example 'web'.
- * @nullable
- */
- lib: string | null;
- /** 'web' for the JavaScript web SDK, 'mobile', 'server', or 'other' for libraries not classified.
- *
- * * `web` - Web
- * * `mobile` - Mobile
- * * `server` - Server
- * * `other` - Other */
- category: SdkLibCategoryEnum;
- /** Multivariate flag calls this SDK sent in the window. */
- calls: number;
- /** Distinct ids that sent those calls. */
- distinct_ids: number;
- /** Share of calls that carry a $device_id. 0 when this SDK never sends one, as server SDKs don't. */
- device_id_share: number;
- /**
- * Share of calls evaluated locally in the SDK instead of by the flags service. Null when no call from this SDK reported it, as the web SDK doesn't.
- * @nullable
- */
- locally_evaluated_share: number | null;
- /**
- * Share of distinct ids that were anonymous, among those that report whether they are identified. Null when no call from this SDK reported it.
- * @nullable
- */
- anonymous_share: number | null;
- }
-
- export interface ExperimentSetupLibActivity {
- /**
- * The $lib value of the SDK, for example 'web'.
- * @nullable
- */
- lib: string | null;
- /** 'web', 'mobile', 'server', or 'other'.
- *
- * * `web` - Web
- * * `mobile` - Mobile
- * * `server` - Server
- * * `other` - Other */
- category: SdkLibCategoryEnum;
- /** Events this SDK sent in the window, of any kind. */
- events: number;
- /** Distinct ids that sent those events. */
- distinct_ids: number;
- }
-
- export interface ExperimentSetupSdkProfile {
- /** Days of flag calls read, ending now. */
- window_days: number;
- /** The event read: '$experiment_exposure' when the project receives it, otherwise '$feature_flag_called'. Only one is read, because one copies the other, and only multivariate responses count either way. This says what the project's events carry today, so it can differ from team_defaults.default_exposure_event, which says what a new experiment would count. */
- source_event: string;
- /** When the numbers were computed. They are cached for hours. */
- computed_at: string;
- /** One row per SDK, most calls first. */
- libs: ExperimentSetupSdkLib[];
- /** True when more SDKs sent flag calls than libs lists. */
- libs_truncated: boolean;
- /** Distinct multivariate flag keys called in the window. */
- flags_seen: number;
- /** How many of those flag keys were called by both a server SDK and the web SDK. */
- flags_evaluated_on_server_and_web: number;
- /** True when at least one flag key was called by both a server SDK and the web SDK. The same flag decided on the server and read in the browser can bucket one user into two variants. */
- evaluated_on_server_and_web: boolean;
- /**
- * Up to 10 SDKs seen on any event over the last day, most events first. Set only when libs is empty, so a project creating its first experiment still says which platforms it sends from. Null when flag calls exist, and null when this extra read timed out.
- * @nullable
- */
- libs_on_any_event: ExperimentSetupLibActivity[] | null;
- /** True when more SDKs sent events than libs_on_any_event lists. False when it is null. */
- libs_on_any_event_truncated: boolean;
- }
-
- export interface ExperimentSetupSdkProfileSection {
- /** 'ok' when data holds the section. 'skipped' when an input the section needs was not passed. 'timed_out' when the query was too expensive to finish. 'error' when the read failed. Every status other than 'ok' leaves data null, and the other sections are still valid.
- *
- * * `ok` - Ok
- * * `skipped` - Skipped
- * * `timed_out` - Timed Out
- * * `error` - Error */
- status: SetupContextSectionStatusEnum;
- /** Which SDKs send multivariate flag calls, across the whole project. */
- data: ExperimentSetupSdkProfile | null;
- }
-
export interface ExperimentSetupLibReach {
/**
* The $lib value that sent the target events.