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): report a variant split changed after launch (#116497)

Marcel Poelker19727bcfef83
diff --git a/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx b/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx
index cde585fd10d7..74a80796393c 100644
--- a/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/healthFindingReporting.test.tsx
@@ -194,11 +194,11 @@ describe('health finding reporting', () => {
const shown = captureSpy.mock.calls
.filter(([event]) => event === 'experiment health finding shown')
- .map(([, properties]) => [properties.finding_code, properties.finding_variant])
+ .map(([, properties]) => [properties.finding_code, properties.finding_variant, properties.finding_severity])
expect(shown).toEqual([
- ['flag_off_while_running', 'running_but_flag_disabled'],
- ['srm', null],
- ['bias_risk_multiple_excluded', null],
+ ['flag_off_while_running', 'running_but_flag_disabled', 'warning'],
+ ['srm', null, 'warning'],
+ ['bias_risk_multiple_excluded', null, 'warning'],
])
})
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 0ec9ba102572..a8aacc1988bd 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -2514,12 +2514,26 @@ describe('experimentLogic', () => {
request_failed: false,
health_finding_codes: ['flag_off_while_running'],
health_finding_subcodes: ['flag_off_while_running:running_but_flag_disabled'],
+ health_findings: ['flag_off_while_running:running_but_flag_disabled:warning:'],
health_finding_count: 1,
flag_state_browser: null,
flag_state_server: 'running_but_flag_disabled',
no_metric_server: false,
},
},
+ {
+ desc: 'an info finding with a reason',
+ overrides: { ...running, feature_flag: flag(true, multivariantFilters) },
+ health: {
+ findings: [
+ {
+ ...healthFinding('split_changed_mid_run', 'not_checked', { reason: 'exposure_filters' }),
+ severity: 'info',
+ },
+ ],
+ },
+ expected: { health_findings: ['split_changed_mid_run:not_checked:info:exposure_filters'] },
+ },
{
desc: 'a server subcode the page does not know',
overrides: { ...running, feature_flag: flag(true, multivariantFilters) },
@@ -2688,6 +2702,8 @@ describe('experimentLogic', () => {
experiment_days_since_start: null,
finding_code: 'flag_live_before_launch',
finding_variant: 'not_started_but_multiple_variants_rolled_out',
+ finding_severity: null,
+ finding_reason: null,
health_ui: 'warnings',
surface: 'experiment_page',
source: 'web',
@@ -2727,6 +2743,8 @@ describe('experimentLogic', () => {
experiment_days_since_start: 3,
finding_code: 'bias_risk_multiple_excluded',
finding_variant: null,
+ finding_severity: null,
+ finding_reason: null,
health_ui: 'panel',
surface: 'experiment_page',
source: 'web',
@@ -2751,6 +2769,8 @@ describe('experimentLogic', () => {
experiment_days_since_start: 3,
finding_code: 'zero_exposures',
finding_variant: null,
+ finding_severity: null,
+ finding_reason: null,
health_ui: 'warnings',
surface: 'experiment_page',
source: 'web',
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 459d3585ce8e..3a92d88941a9 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -245,6 +245,7 @@ const HEALTH_CHECK_INPUTS = [
'end_date',
'archived',
'stats_config',
+ 'exposure_criteria',
] as const satisfies readonly (keyof Experiment)[]
function healthCheckInputs(experiment: Experiment): Partial<Experiment> {
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 9fda1bc234c2..f295a326e180 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -9990,6 +9990,7 @@ export namespace Schemas {
* * `zero_exposures` - Zero Exposures
* * `forced_variant_release_condition` - Forced Variant Release Condition
* * `flag_variants_mismatch` - Flag Variants Mismatch
+ * * `split_changed_mid_run` - Split Changed Mid Run
*/
export type ExperimentHealthFindingCodeEnum =
| "flag_off_while_running"
@@ -10001,7 +10002,8 @@ export namespace Schemas {
| "srm"
| "zero_exposures"
| "forced_variant_release_condition"
- | "flag_variants_mismatch";
+ | "flag_variants_mismatch"
+ | "split_changed_mid_run";
/**
* * `critical` - Critical severity
* * `warning` - Warning severity
@@ -10013,6 +10015,7 @@ export namespace Schemas {
| "info";
/**
* * `open_feature_flag` - Open Feature Flag
+ * * `open_feature_flag_history` - Open Feature Flag History
* * `adjust_distribution` - Adjust Distribution
* * `use_first_seen_variant` - Use First Seen Variant
* * `add_primary_metric` - Add Primary Metric
@@ -10022,6 +10025,7 @@ export namespace Schemas {
*/
export type ExperimentHealthFindingActionKindEnum =
| "open_feature_flag"
+ | "open_feature_flag_history"
| "adjust_distribution"
| "use_first_seen_variant"
| "add_primary_metric"
@@ -10042,6 +10046,7 @@ export namespace Schemas {
* * `zero_exposures` - Zero Exposures
* * `forced_variant_release_condition` - Forced Variant Release Condition
* * `flag_variants_mismatch` - Flag Variants Mismatch
+ * * `split_changed_mid_run` - Split Changed Mid Run
*/
code: ExperimentHealthFindingCodeEnum;
/**
@@ -10067,7 +10072,7 @@ export namespace Schemas {
/**
* The values behind the finding, such as the key of a shipped variant or the share of users exposed to multiple variants. The keys depend on the code.
*/
- evidence: Record<string, string | number | null>;
+ evidence: Record<string, string | number | boolean | null>;
/**
* The actions that fix the problem, in order of preference, for example 'open_feature_flag' or 'add_primary_metric'.
*/
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 60631f66cbc9..ef9f84a57c58 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -49,6 +49,7 @@ from posthog.utils import str_to_bool
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models import EventDefinition, effective_project_id_expr
+from products.experiments.backend.facade.contracts import ExperimentHealthFinding
from products.experiments.backend.facade.launch_signals import experiment_launched
from products.experiments.backend.flag_cleanup import build_cleanup_prompt, cleanup_plan
from products.experiments.backend.health.context import load_health_context
@@ -344,6 +345,15 @@ def _apply_holdout(filters: dict, holdout: ExperimentHoldout | None) -> dict:
)
+def _tracked_health_finding(finding: ExperimentHealthFinding) -> str:
+ # pinned: `code:subcode:severity:reason`, as on the page's `experiment health checked`. Insights split each
+ # string on `:`, so every field is present, empty when the finding has none.
+ reason = finding.evidence.get("reason")
+ return ":".join(
+ [finding.code.value, finding.subcode or "", finding.severity.value, reason if isinstance(reason, str) else ""]
+ )
+
+
class ExperimentVersionConflict(APIException):
"""A stale write raced a concurrent update and could not be applied safely."""
@@ -1403,6 +1413,7 @@ class ExperimentService:
"health_finding_subcodes": [
f"{finding.code.value}:{finding.subcode}" for finding in findings if finding.subcode
],
+ "health_findings": [_tracked_health_finding(finding) for finding in findings],
"health_finding_count": len(findings),
},
)
diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.py
index 0c700f5f3359..b6085267ed68 100644
--- a/products/experiments/backend/facade/api.py
+++ b/products/experiments/backend/facade/api.py
@@ -14,6 +14,7 @@ from posthog.models.user import User
from products.experiments.backend.experiment_service import ExperimentService
from products.experiments.backend.health.context import load_health_context
+from products.experiments.backend.health.exposure_gate import load_split_history
from products.experiments.backend.health.registry import (
EXPERIMENT_HEALTH_CHECKS,
evaluate as evaluate_health,
@@ -25,7 +26,7 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (
)
from products.experiments.backend.models.experiment import Experiment as ExperimentModel
-from .contracts import CreateExperimentInput, Experiment, ExperimentHealthFinding
+from .contracts import CreateExperimentInput, Experiment, ExperimentHealthFinding, ExperimentHealthReaderAccess
def create_experiment(*, team: Team, user: User, input_dto: CreateExperimentInput) -> Experiment:
@@ -125,15 +126,20 @@ def count_running_experiments_on_feature_flag_called(organization_id: UUID) -> i
return count
-def get_experiment_health_findings(*, team_id: int, experiment_id: int) -> list[ExperimentHealthFinding]:
- """The findings of the health checks that read only the experiment, its flag and its linked metrics."""
+def get_experiment_health_findings(
+ *, team_id: int, experiment_id: int, reader_access: ExperimentHealthReaderAccess
+) -> 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 as far as `reader_access` allows."""
experiment = (
ExperimentModel.objects.filter(team_id=team_id)
- .select_related("feature_flag")
+ .select_related("team", "feature_flag")
.prefetch_related("experimenttosavedmetric_set")
.get(id=experiment_id)
)
- return evaluate_health(load_health_context(experiment), EXPERIMENT_HEALTH_CHECKS)
+ split_history = load_split_history(experiment, reader_access=reader_access)
+ context = load_health_context(experiment, split_history=split_history)
+ return evaluate_health(context, EXPERIMENT_HEALTH_CHECKS)
def _experiment_model_to_dto(experiment: ExperimentModel) -> Experiment:
diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.py
index 6338d953096e..6b1100ff205f 100644
--- a/products/experiments/backend/facade/contracts.py
+++ b/products/experiments/backend/facade/contracts.py
@@ -108,6 +108,7 @@ class ExperimentHealthFindingCode(LabeledStrEnum):
ZERO_EXPOSURES = "zero_exposures"
FORCED_VARIANT_RELEASE_CONDITION = "forced_variant_release_condition"
FLAG_VARIANTS_MISMATCH = "flag_variants_mismatch"
+ SPLIT_CHANGED_MID_RUN = "split_changed_mid_run"
class ExperimentHealthFindingSeverity(LabeledStrEnum):
@@ -121,6 +122,7 @@ class ExperimentHealthFindingSeverity(LabeledStrEnum):
class ExperimentHealthFindingActionKind(LabeledStrEnum):
OPEN_FEATURE_FLAG = "open_feature_flag"
+ OPEN_FEATURE_FLAG_HISTORY = "open_feature_flag_history"
ADJUST_DISTRIBUTION = "adjust_distribution"
USE_FIRST_SEEN_VARIANT = "use_first_seen_variant"
ADD_PRIMARY_METRIC = "add_primary_metric"
@@ -138,11 +140,19 @@ class ExperimentHealthFinding:
severity: ExperimentHealthFindingSeverity
title: str
detail: str
- evidence: Mapping[str, str | int | float | None]
+ evidence: Mapping[str, str | int | float | bool | None]
actions: tuple[ExperimentHealthFindingActionKind, ...]
diagnostic_ref: str | None
+@frozen
+class ExperimentHealthReaderAccess:
+ """What the caller of the health checks may read, for the checks that read more than the experiment."""
+
+ can_read_flag_history: bool
+ can_query_events: bool
+
+
@dataclass(frozen=True)
class CreateExperimentInput:
"""
diff --git a/products/experiments/backend/health/checks/flag_state.py b/products/experiments/backend/health/checks/flag_state.py
index f1cd794de3ac..5323605d8a87 100644
--- a/products/experiments/backend/health/checks/flag_state.py
+++ b/products/experiments/backend/health/checks/flag_state.py
@@ -12,7 +12,13 @@ from products.experiments.backend.facade.contracts import (
ExperimentHealthFindingCode,
ExperimentHealthFindingSeverity,
)
-from products.experiments.backend.health.context import FlagState, HealthContext
+from products.experiments.backend.health.context import FlagState, HealthContext, SplitHistoryNotChecked
+from products.experiments.backend.health.split_changes import (
+ SplitChangeShape,
+ describe_split,
+ format_change_time,
+ net_effect,
+)
# pinned: the page's warning keys. The page sends them as `finding_variant` and
# `warning_key` on its events, and picks the banner text by them.
@@ -83,7 +89,8 @@ def flag_state(ctx: HealthContext) -> ExperimentHealthFinding | None:
subcode=RUNNING_BUT_SINGLE_VARIANT_SHIPPED,
title="The experiment is running, but all users see a single variant",
detail=(
- f"{shipped} rolled out to 100% of users. The experiment is not comparing variants. "
+ f"{shipped} rolled out to 100% of users. {_rollout_since(ctx)}"
+ "The experiment is not comparing variants. "
"End the experiment with a conclusion, or adjust the variant distribution of the linked "
"feature flag to resume proper A/B testing."
),
@@ -136,6 +143,18 @@ def _finding(
)
+def _rollout_since(ctx: HealthContext) -> str:
+ # The split check leaves this rollout to this finding, so the finding carries the date of the change.
+ history = ctx.split_history
+ if history is None:
+ return ""
+ effect = net_effect(history.changes if isinstance(history, SplitHistoryNotChecked) else history.counted_changes)
+ if effect is None or effect.shape != SplitChangeShape.VARIANT_ROLLED_OUT:
+ return ""
+ at = format_change_time(effect.last.changed_at, history.team_timezone)
+ return f"It has been at 100% since {at}, and the split was {describe_split(effect.last.before)} before. "
+
+
def _has_zero_rollout(flag: FlagState) -> bool:
# Only true when every release group is set to 0 explicitly. A group without a rollout
# percentage serves everyone.
diff --git a/products/experiments/backend/health/checks/split_changed.py b/products/experiments/backend/health/checks/split_changed.py
new file mode 100644
index 000000000000..d2de7e60e5ad
--- /dev/null
+++ b/products/experiments/backend/health/checks/split_changed.py
@@ -0,0 +1,369 @@
+"""
+A variant split of the experiment's flag that changed after launch while people were already exposed. Pure
+functions, no I/O: `health/exposure_gate.py` loads the changes and the exposure answers.
+
+People exposed before such a change can get another variant after it, so the results mix two assignments.
+"""
+
+from datetime import UTC, timedelta
+from typing import Literal
+
+from products.experiments.backend.facade.contracts import (
+ ExperimentHealthFinding,
+ ExperimentHealthFindingActionKind,
+ ExperimentHealthFindingCode,
+ ExperimentHealthFindingSeverity,
+)
+from products.experiments.backend.health.checks.flag_state import is_single_variant_shipped
+from products.experiments.backend.health.context import (
+ FlagState,
+ HealthContext,
+ SplitHistory,
+ SplitHistoryNotChecked,
+ SplitHistoryNotCheckedReason,
+)
+from products.experiments.backend.health.split_changes import (
+ SplitChangeShape,
+ SplitNetEffect,
+ added_variant_keys,
+ describe_split,
+ format_change_time,
+ net_effect,
+ removed_variant_keys,
+ rolled_out_variant_key,
+ zeroed_variant_keys,
+)
+
+# pinned: the subcode of a split history that was not checked against the exposures. The page sends it as
+# `finding_variant` on the health finding events.
+NOT_CHECKED = "not_checked"
+
+_TITLE = "The variant split changed after launch"
+_REVERTED_INFO_TITLE = "The variant split changed and was set back"
+_NOT_CHECKED_TITLE = "Variant split changes were not checked"
+_HISTORY_NOT_CHECKED_TITLE = "The variant split history was not checked"
+_SECONDS_PER_DAY = 24 * 60 * 60
+
+
+def split_changed_mid_run(ctx: HealthContext) -> ExperimentHealthFinding | None:
+ history = ctx.split_history
+ flag = ctx.flag
+ if history is None or flag is None or flag.deleted or not ctx.is_running or ctx.archived:
+ return None
+ # `flag_variants_mismatch` reports a flag without variants, and the variants have to come back first.
+ if not any(variant.key for variant in flag.variants):
+ return None
+ if isinstance(history, SplitHistoryNotChecked):
+ return _not_checked(history, flag)
+ effect = net_effect(history.counted_changes)
+ if effect is None or _reported_as_shipped(effect, flag):
+ return None
+
+ if effect.shape == SplitChangeShape.REVERTED and history.exposed_between is False:
+ return _finding(
+ history,
+ effect,
+ severity=ExperimentHealthFindingSeverity.INFO,
+ title=_REVERTED_INFO_TITLE,
+ sentences=[*_reverted(history, effect), "Nobody was exposed in between."],
+ )
+ if effect.shape == SplitChangeShape.REVERTED:
+ start_at = _suggested_start(history, effect)
+ return _finding(
+ history,
+ effect,
+ severity=ExperimentHealthFindingSeverity.WARNING,
+ title=_TITLE,
+ sentences=[
+ *_reverted(history, effect),
+ *_delay(history, effect),
+ "People exposed in between may have switched variants.",
+ f"Move the start date to {start_at}, or reset the experiment.",
+ ],
+ )
+ return _finding(
+ history,
+ effect,
+ severity=ExperimentHealthFindingSeverity.WARNING,
+ title=_TITLE,
+ sentences=[
+ _what_changed(history, effect),
+ *_delay(history, effect),
+ *_consequence(history, effect),
+ f"A sample ratio mismatch or users in more than one variant can come from {_the_change(effect, 'this')}.",
+ ],
+ )
+
+
+def _not_checked(history: SplitHistoryNotChecked, flag: FlagState) -> ExperimentHealthFinding | None:
+ if history.reason == SplitHistoryNotCheckedReason.NO_HISTORY_ACCESS:
+ return ExperimentHealthFinding(
+ code=ExperimentHealthFindingCode.SPLIT_CHANGED_MID_RUN,
+ subcode=NOT_CHECKED,
+ severity=ExperimentHealthFindingSeverity.INFO,
+ title=_HISTORY_NOT_CHECKED_TITLE,
+ detail=(
+ "This check can't see whether the variant split changed after launch, because "
+ f"{_not_checked_because(history.reason)}. Viewing the history needs viewer access to the flag and, "
+ "with an API key, the activity_log:read scope."
+ ),
+ evidence={"reason": history.reason.value},
+ # The flag history is the page this caller can't open.
+ actions=(),
+ diagnostic_ref="E3",
+ )
+ effect = net_effect(history.changes)
+ if effect is None or _reported_as_shipped(effect, flag):
+ return None
+ the_change = _the_change(effect, "the")
+ at = format_change_time(effect.last.changed_at, history.team_timezone)
+ from_split = describe_split(effect.from_split)
+ if effect.shape == SplitChangeShape.REVERTED:
+ what_changed = (
+ f"The variant split changed {effect.change_count} times after launch and was set back to "
+ f"{from_split} on {at}."
+ )
+ elif effect.change_count > 1:
+ what_changed = (
+ f"The variant split changed {effect.change_count} times after launch, from {from_split} to "
+ f"{describe_split(effect.to_split)}, last on {at}."
+ )
+ else:
+ what_changed = f"The variant split changed from {from_split} to {describe_split(effect.to_split)} on {at}."
+ next_step = (
+ f"Add the query:read scope to this API key, or review {the_change} in the flag history."
+ if history.reason == SplitHistoryNotCheckedReason.NO_QUERY_ACCESS
+ else f"Review {the_change} in the flag history."
+ )
+ return ExperimentHealthFinding(
+ code=ExperimentHealthFindingCode.SPLIT_CHANGED_MID_RUN,
+ subcode=NOT_CHECKED,
+ severity=ExperimentHealthFindingSeverity.INFO,
+ title=_NOT_CHECKED_TITLE,
+ detail=" ".join(
+ [
+ what_changed,
+ f"This check can't tell whether anyone was exposed before {the_change}, because "
+ f"{_not_checked_because(history.reason)}.",
+ next_step,
+ ]
+ ),
+ evidence={"reason": history.reason.value, **_change_evidence(history, effect, exposed_before_change=None)},
+ actions=(ExperimentHealthFindingActionKind.OPEN_FEATURE_FLAG_HISTORY,),
+ diagnostic_ref="E3",
+ )
+
+
+def _not_checked_because(reason: SplitHistoryNotCheckedReason) -> str:
+ match reason:
+ case SplitHistoryNotCheckedReason.EXPOSURE_FILTERS:
+ return "the exposure criteria filter by properties"
+ case SplitHistoryNotCheckedReason.EXPOSURE_ACTION:
+ return "exposures come from an action"
+ case SplitHistoryNotCheckedReason.EXPOSURE_CRITERIA:
+ return "the exposure criteria can't be read"
+ case SplitHistoryNotCheckedReason.NO_QUERY_ACCESS:
+ return "this API key can't query events"
+ case SplitHistoryNotCheckedReason.NO_HISTORY_ACCESS:
+ return "you can't view the linked feature flag's history"
+
+
+def _reported_as_shipped(effect: SplitNetEffect, flag: FlagState) -> bool:
+ # `variant_shipped_while_running` reports this state, and its detail carries the date of the rollout.
+ return effect.shape == SplitChangeShape.VARIANT_ROLLED_OUT and is_single_variant_shipped(flag)
+
+
+def _what_changed(history: SplitHistory, effect: SplitNetEffect) -> str:
+ from_split = describe_split(effect.from_split)
+ to_split = describe_split(effect.to_split)
+ at = format_change_time(effect.last.changed_at, history.team_timezone)
+ if effect.change_count > 1:
+ # Changes before the first exposure are not counted, so the count names its own span. "Since launch"
+ # would undercount what the flag history shows.
+ first_at = format_change_time(effect.first.changed_at, history.team_timezone)
+ return (
+ f"The split changed {effect.change_count} times between {first_at} and {at}, "
+ f"from {from_split} to {to_split}."
+ )
+ match effect.shape:
+ case SplitChangeShape.VARIANT_ROLLED_OUT:
+ variant = _rolled_out_variant(effect, starts_sentence=True)
+ return f"{variant} was set to 100% of the split on {at}, while the experiment is still running."
+ case SplitChangeShape.VARIANT_REMOVED:
+ keys = removed_variant_keys(effect.from_split, effect.to_split)
+ return f"{_variants(keys)} {_was(keys)} removed on {at} (from {from_split} to {to_split})."
+ case SplitChangeShape.VARIANT_ADDED:
+ keys = added_variant_keys(effect.from_split, effect.to_split)
+ return f"{_variants(keys)} {_was(keys)} added on {at} (from {from_split} to {to_split})."
+ case SplitChangeShape.VARIANT_ZEROED:
+ keys = zeroed_variant_keys(effect.from_split, effect.to_split)
+ return f"{_variants(keys)} {_was(keys)} set to 0% on {at} (from {from_split} to {to_split})."
+ case SplitChangeShape.REORDERED:
+ return f"The order of the variants changed on {at} (from {from_split} to {to_split})."
+ case _:
+ return f"The split changed from {from_split} to {to_split} on {at}."
+
+
+def _consequence(history: SplitHistory, effect: SplitNetEffect) -> list[str]:
+ start_at = _suggested_start(history, effect)
+ the_change = _the_change(effect, "the")
+ match effect.shape:
+ case SplitChangeShape.VARIANT_ROLLED_OUT:
+ variant = _rolled_out_variant(effect, starts_sentence=False)
+ return [
+ f"From then on, the split assigns everyone to {variant}.",
+ "End the experiment with a conclusion, or restore the split.",
+ ]
+ case SplitChangeShape.VARIANT_REMOVED:
+ keys = _quoted(removed_variant_keys(effect.from_split, effect.to_split), conjunction="or")
+ return [
+ f"The results leave out people who saw only {keys}, and people who had {keys} may now get "
+ "another variant.",
+ f"Reset the experiment, or move its start date to {start_at}.",
+ ]
+ case SplitChangeShape.VARIANT_ADDED:
+ return [
+ f"People exposed before {the_change} may have switched variants.",
+ f"Reset the experiment, or move its start date to {start_at}.",
+ ]
+ case SplitChangeShape.VARIANT_ZEROED:
+ # The zeroed share goes to other variants, which moves their boundaries too. Excluding the zeroed
+ # variant from the analysis therefore leaves mixed assignments in the variants that remain.
+ keys = _quoted(zeroed_variant_keys(effect.from_split, effect.to_split), conjunction="and")
+ return [
+ f"People exposed before {the_change} may have switched variants, and no new users get {keys}.",
+ f"Reset the experiment, or move its start date to {start_at}.",
+ ]
+ case SplitChangeShape.REORDERED:
+ # Restoring the order moves the people exposed since the change a second time.
+ return [
+ f"The order decides who gets which variant, so people exposed before {the_change} may have "
+ "switched variants.",
+ f"Reset the experiment, or move its start date to {start_at}.",
+ ]
+ case _:
+ return [
+ f"People exposed before {the_change} may have switched variants, so the results mix two assignments.",
+ f"Reset the experiment, or move its start date to {start_at} to analyze only the people exposed "
+ f"after {the_change}.",
+ ]
+
+
+def _reverted(history: SplitHistory, effect: SplitNetEffect) -> list[str]:
+ first_at = format_change_time(effect.first.changed_at, history.team_timezone)
+ last_at = format_change_time(effect.last.changed_at, history.team_timezone)
+ from_split = describe_split(effect.from_split)
+ if effect.change_count > 2:
+ return [
+ f"The split changed {effect.change_count} times between {first_at} and {last_at}, "
+ f"and was set back to {from_split}."
+ ]
+ changed_to = describe_split(effect.first.after)
+ if history.exposed_between is False:
+ span = _duration((effect.last.changed_at - effect.first.changed_at).total_seconds())
+ return [f"The split was set to {changed_to} on {first_at} and set back {span} later."]
+ return [f"The split was set to {changed_to} on {first_at} and set back to {from_split} on {last_at}."]
+
+
+def _delay(history: SplitHistory, effect: SplitNetEffect) -> list[str]:
+ # When nobody knows whether anyone was exposed before the change, or the change came days after launch,
+ # the time since launch tells the reader how many people the change can have moved.
+ seconds = _seconds_after_launch(history, effect)
+ if history.exposed_before_first is not None and seconds <= _SECONDS_PER_DAY:
+ return []
+ change = "The change" if effect.change_count == 1 else "The first change"
+ return [f"{change} came {_duration(seconds)} after launch."]
+
+
+def _finding(
+ history: SplitHistory,
+ effect: SplitNetEffect,
+ *,
+ severity: ExperimentHealthFindingSeverity,
+ title: str,
+ sentences: list[str],
+) -> ExperimentHealthFinding:
+ return ExperimentHealthFinding(
+ code=ExperimentHealthFindingCode.SPLIT_CHANGED_MID_RUN,
+ subcode=effect.shape.value,
+ severity=severity,
+ title=title,
+ detail=" ".join(sentences),
+ evidence=_change_evidence(history, effect, exposed_before_change=history.exposed_before_first),
+ actions=(ExperimentHealthFindingActionKind.OPEN_FEATURE_FLAG_HISTORY,),
+ diagnostic_ref=(
+ "E4" if effect.shape in (SplitChangeShape.VARIANT_ADDED, SplitChangeShape.VARIANT_REMOVED) else "E3"
+ ),
+ )
+
+
+def _change_evidence(
+ history: SplitHistory | SplitHistoryNotChecked, effect: SplitNetEffect, *, exposed_before_change: bool | None
+) -> dict[str, str | int | bool | None]:
+ return {
+ "change_count": effect.change_count,
+ "first_changed_at": effect.first.changed_at.astimezone(UTC).isoformat(),
+ "last_changed_at": effect.last.changed_at.astimezone(UTC).isoformat(),
+ "from": describe_split(effect.from_split),
+ "to": describe_split(effect.to_split),
+ "exposed_before_change": exposed_before_change,
+ "seconds_after_launch": int(_seconds_after_launch(history, effect)),
+ }
+
+
+def _suggested_start(history: SplitHistory, effect: SplitNetEffect) -> str:
+ # The start date picker saves whole minutes, so a start inside the minute of the change keeps exposures
+ # from before it.
+ changed_at = effect.last.changed_at
+ minute = changed_at.replace(second=0, microsecond=0)
+ start = minute if minute == changed_at else minute + timedelta(minutes=1)
+ return format_change_time(start, history.team_timezone)
+
+
+def _seconds_after_launch(history: SplitHistory | SplitHistoryNotChecked, effect: SplitNetEffect) -> float:
+ return (effect.first.changed_at - history.launched_at).total_seconds()
+
+
+def _the_change(effect: SplitNetEffect, determiner: Literal["the", "this"]) -> str:
+ if effect.change_count == 1:
+ return f"{determiner} change"
+ return "the changes" if determiner == "the" else "these changes"
+
+
+def _rolled_out_variant(effect: SplitNetEffect, *, starts_sentence: bool) -> str:
+ key = rolled_out_variant_key(effect.to_split)
+ if key:
+ return f'{"Variant" if starts_sentence else "variant"} "{key}"'
+ return "One variant" if starts_sentence else "one variant"
+
+
+def _was(keys: list[str]) -> str:
+ return "was" if len(keys) == 1 else "were"
+
+
+def _variants(keys: list[str]) -> str:
+ noun = "Variant" if len(keys) == 1 else "Variants"
+ return f"{noun} {_quoted(keys, conjunction='and')}"
+
+
+def _quoted(keys: list[str], *, conjunction: Literal["and", "or"]) -> str:
+ quoted = [f'"{key}"' for key in keys]
+ if len(quoted) <= 1:
+ return "".join(quoted)
+ return f"{', '.join(quoted[:-1])} {conjunction} {quoted[-1]}"
+
+
+def _duration(seconds: float) -> str:
+ minutes = int(seconds // 60)
+ if minutes < 1:
+ return "less than a minute"
+ if minutes < 60:
+ return _count(minutes, "minute")
+ hours = minutes // 60
+ if hours < 48:
+ return _count(hours, "hour")
+ return _count(hours // 24, "day")
+
+
+def _count(value: int, unit: str) -> str:
+ return f"{value} {unit}" if value == 1 else f"{value} {unit}s"
diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.py
index d48e3590ac51..86bf36426699 100644
--- a/products/experiments/backend/health/context.py
+++ b/products/experiments/backend/health/context.py
@@ -1,4 +1,6 @@
from collections.abc import Mapping
+from datetime import datetime
+from enum import StrEnum
from posthog.schema import MultipleVariantHandling
@@ -15,6 +17,52 @@ class FlagVariant:
rollout_percentage: float | None
+Split = tuple[FlagVariant, ...]
+
+
+@frozen
+class SplitChange:
+ changed_at: datetime
+ before: Split
+ after: Split
+
+
+@frozen
+class SplitHistory:
+ """The changes of the flag's split after launch that can have moved exposed people to another variant."""
+
+ launched_at: datetime
+ team_timezone: str
+ # 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, ...]
+ # None when unknown: the exposure query failed, or the request ran out of queries or time.
+ exposed_before_first: bool | None
+ # Asked only when the last change sets the split back to what it was before the first. None when not
+ # asked, or unknown.
+ exposed_between: bool | None
+
+
+class SplitHistoryNotCheckedReason(StrEnum):
+ # pinned: the finding's `evidence.reason`.
+ NO_HISTORY_ACCESS = "no_history_access"
+ NO_QUERY_ACCESS = "no_query_access"
+ EXPOSURE_FILTERS = "exposure_filters"
+ EXPOSURE_ACTION = "exposure_action"
+ EXPOSURE_CRITERIA = "exposure_criteria"
+
+
+@frozen
+class SplitHistoryNotChecked:
+ """A split history that was not compared with the exposures, and the reason."""
+
+ reason: SplitHistoryNotCheckedReason
+ launched_at: datetime
+ team_timezone: str
+ # Every split change since launch. Empty for NO_HISTORY_ACCESS, which does not read them.
+ changes: tuple[SplitChange, ...]
+
+
@frozen
class FlagReleaseGroup:
rollout_percentage: float | None
@@ -62,6 +110,8 @@ class HealthContext:
primary_metric_count: int
secondary_metric_count: int
exposures: ExposureTotals | None
+ # None when not loaded. Only the health endpoint loads it, because it can query the exposures.
+ split_history: SplitHistory | SplitHistoryNotChecked | None
def parse_flag_state(
@@ -74,7 +124,7 @@ def parse_flag_state(
early_exit: bool = False,
) -> FlagState:
conditions = groups if isinstance(groups, list) else []
- flag_variants = tuple(_variant(variant) for variant in variants) if isinstance(variants, list) else ()
+ flag_variants = parse_variants(variants)
variant_keys = {variant.key for variant in flag_variants if variant.key}
reachable = reachable_conditions(conditions, flag_aggregation=aggregation_group_type_index, early_exit=early_exit)
return FlagState(
@@ -109,6 +159,10 @@ def _variant(variant: object) -> FlagVariant:
)
+def parse_variants(variants: object) -> Split:
+ return tuple(_variant(variant) for variant in variants) if isinstance(variants, list) else ()
+
+
def _percentage(value: object) -> float | None:
# The page compares with `=== 0` and `=== 100`, so only a JSON number can match. A string or a
# boolean must not, and Python's `False == 0` would let a boolean through.
@@ -139,7 +193,12 @@ def _configured_baseline_variant_key(stats_config: object) -> str | None:
return key if isinstance(key, str) and key else None
-def load_health_context(experiment: Experiment, exposures: ExposureTotals | None = None) -> HealthContext:
+def load_health_context(
+ experiment: Experiment,
+ exposures: ExposureTotals | None = None,
+ *,
+ split_history: SplitHistory | SplitHistoryNotChecked | None = None,
+) -> HealthContext:
shared_metric_roles = [saved_metric_link_role(link) for link in saved_metric_links(experiment)]
return HealthContext(
is_launched=experiment.is_launched,
@@ -152,4 +211,5 @@ def load_health_context(experiment: Experiment, exposures: ExposureTotals | None
primary_metric_count=len(experiment.metrics or []) + shared_metric_roles.count("primary"),
secondary_metric_count=len(experiment.metrics_secondary or []) + shared_metric_roles.count("secondary"),
exposures=exposures,
+ split_history=split_history,
)
diff --git a/products/experiments/backend/health/exposure_gate.py b/products/experiments/backend/health/exposure_gate.py
new file mode 100644
index 000000000000..23e3658bfdec
--- /dev/null
+++ b/products/experiments/backend/health/exposure_gate.py
@@ -0,0 +1,356 @@
+"""
+Loads the split changes of a running experiment's flag since launch, and asks ClickHouse whether anyone was
+exposed before each change. A change before the first exposure moved nobody, so it does not count.
+
+The answer for a past window does not change, so it is cached per window and shared by every reader. A slow
+answer is then paid once per change, not on every load of the experiment page. A failed query is cached as
+unknown too, so a scan that is too large for a request runs at most once a day.
+
+Only exposure criteria that name an event are asked about. The answer for a property filter or an action can
+depend on what each reader may read, and can change as the filter matches other events over time, so no cached
+answer for them is safe to share. The split changes of those experiments are reported as not checked.
+"""
+
+import json
+import hashlib
+from collections.abc import Sequence
+from datetime import datetime, timedelta
+from time import monotonic
+
+from django.core.cache import cache
+from django.db.models import F, Func, JSONField, Value
+from django.db.models.fields.json import KT
+from django.utils import timezone
+
+import pydantic
+
+from posthog.schema import ActionsNode
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.dataclasses import frozen
+from posthog.errors import CH_TRANSIENT_ERRORS
+from posthog.exceptions import (
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQueryTimeOut,
+)
+from posthog.exceptions_capture import capture_exception
+from posthog.models.activity_logging.activity_log import ActivityLog
+
+from products.experiments.backend.facade.contracts import ExperimentHealthReaderAccess
+from products.experiments.backend.health.context import (
+ SplitChange,
+ SplitHistory,
+ SplitHistoryNotChecked,
+ SplitHistoryNotCheckedReason,
+)
+from products.experiments.backend.health.split_changes import (
+ same_assignment,
+ split_change_from_activity,
+ split_variant_keys,
+)
+from products.experiments.backend.hogql_queries.exposure_query_logic import (
+ build_exposure_event_conditions,
+ get_exposure_event_and_property,
+ normalize_to_exposure_criteria,
+ resolve_default_exposure_event,
+)
+from products.experiments.backend.models.experiment import Experiment
+
+MAX_EXPOSURE_QUERIES = 20
+EXPOSURE_QUERY_TIMEOUT_SECONDS = 10
+# No query starts after this, so one request takes at most this plus one query's timeout.
+REQUEST_BUDGET_SECONDS = 10
+_ANSWER_CACHE_SECONDS = int(timedelta(days=30).total_seconds())
+# A scan too large for a request stays too large, so it waits a day. Another error can be brief, and an
+# unknown answer shows the finding, so it waits an hour.
+_TOO_EXPENSIVE_CACHE_SECONDS = int(timedelta(days=1).total_seconds())
+_FAILED_CACHE_SECONDS = int(timedelta(hours=1).total_seconds())
+_UNKNOWN = "unknown"
+_BEFORE_VARIANTS_PATH = '$.changes[*] ? (@.field == "filters").before.multivariate.variants'
+_AFTER_VARIANTS_PATH = '$.changes[*] ? (@.field == "filters").after.multivariate.variants'
+# Events can arrive after the window ends, so a "nobody" answer for a recent window can still change.
+_SETTLED_AFTER = timedelta(hours=1)
+# A recent "nobody" is kept briefly, so page loads in that hour do not each run the scan again.
+_RECENT_NOBODY_CACHE_SECONDS = int(timedelta(minutes=5).total_seconds())
+# The scan is too large for a request. These are expected, so they are not reported.
+_TOO_EXPENSIVE_ERRORS = (
+ ClickHouseQueryTimeOut,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+)
+
+
+def load_split_history(
+ experiment: Experiment, *, reader_access: ExperimentHealthReaderAccess
+) -> SplitHistory | SplitHistoryNotChecked | None:
+ """
+ The split history of a running, not archived experiment whose flag exists and is not deleted, or None.
+ Never raises: the health endpoint serves the other findings when this fails.
+ """
+ try:
+ return _load_split_history(experiment, reader_access)
+ except Exception as error:
+ capture_exception(error)
+ return None
+
+
+def query_any_exposure(
+ experiment: Experiment,
+ *,
+ window_start: datetime,
+ window_end: datetime,
+ variant_keys: Sequence[str],
+ default_exposure_event: str,
+) -> bool:
+ """Whether anyone was exposed to one of the variant keys in `[window_start, window_end)`."""
+ team = experiment.team
+ flag_key = experiment.get_feature_flag_key()
+ _, variant_property = get_exposure_event_and_property(
+ flag_key, experiment.exposure_criteria, default_exposure_event=default_exposure_event
+ )
+ # No test-account filter, as in the exposure freeze: the question is whether the flag served anyone.
+ query = parse_select(
+ """
+ SELECT 1 FROM events
+ WHERE timestamp >= {window_start} AND timestamp < {window_end} AND {exposure} AND {variant} IN {variant_keys}
+ LIMIT 1
+ """,
+ placeholders={
+ "window_start": ast.Constant(value=window_start),
+ "window_end": ast.Constant(value=window_end),
+ "exposure": ast.And(
+ exprs=build_exposure_event_conditions(
+ experiment.exposure_criteria, team, flag_key, default_exposure_event=default_exposure_event
+ )
+ ),
+ "variant": ast.Field(chain=["properties", variant_property]),
+ "variant_keys": ast.Constant(value=list(variant_keys)),
+ },
+ )
+ with tags_context(
+ product=Product.EXPERIMENTS, feature=Feature.HEALTH_CHECK, team_id=team.pk, org_id=team.organization_id
+ ):
+ # No user, as in the exposure freeze, because every reader gets the cached answer.
+ response = execute_hogql_query(
+ query,
+ team=team,
+ # A profile that breaks on timeout returns no rows, which would read as "nobody exposed".
+ settings=HogQLGlobalSettings(
+ max_execution_time=EXPOSURE_QUERY_TIMEOUT_SECONDS, timeout_overflow_mode="throw"
+ ),
+ )
+ return bool(response.results)
+
+
+@frozen
+class _Window:
+ start: datetime
+ end: datetime
+ variant_keys: tuple[str, ...]
+
+
+class _ExposureGate:
+ """
+ Answers the exposure questions of one request from the cache, or with at most MAX_EXPOSURE_QUERIES queries
+ that start within REQUEST_BUDGET_SECONDS.
+ """
+
+ def __init__(self, experiment: Experiment, launched_at: datetime, *, prefetch: Sequence[_Window]) -> None:
+ self._experiment = experiment
+ self._launched_at = launched_at
+ self._default_exposure_event = resolve_default_exposure_event(experiment.team, launched_at)
+ # One cache read for all windows of the walk, so a flag with many changes costs one round trip.
+ self._prefetched_keys = {self._cache_key(window) for window in prefetch if window.variant_keys}
+ self._prefetched = cache.get_many(list(self._prefetched_keys))
+ self._started_at = monotonic()
+ self._query_count = 0
+ self._stopped = False
+
+ def exposed(self, window: _Window) -> bool | None:
+ """None when unknown: the query failed in this request or within its cache time, or the request is out of budget."""
+ if not window.variant_keys:
+ return False
+ cache_key = self._cache_key(window)
+ cached = self._prefetched.get(cache_key) if cache_key in self._prefetched_keys else cache.get(cache_key)
+ if isinstance(cached, bool):
+ return cached
+ if cached == _UNKNOWN:
+ return None
+ if self._stopped:
+ return None
+ if self._query_count >= MAX_EXPOSURE_QUERIES or monotonic() - self._started_at >= REQUEST_BUDGET_SECONDS:
+ # Every answer is cached on its own, so the next request continues the walk where this one stopped.
+ self._stopped = True
+ return None
+ self._query_count += 1
+ try:
+ answer = query_any_exposure(
+ self._experiment,
+ window_start=window.start,
+ window_end=window.end,
+ variant_keys=window.variant_keys,
+ default_exposure_event=self._default_exposure_event,
+ )
+ except Exception as error:
+ # The page calls the endpoint on every load, so a scan that fails must not run again on every load.
+ # Cluster memory pressure subclasses the per-query memory error, but it says nothing about this scan.
+ transient = isinstance(error, CH_TRANSIENT_ERRORS)
+ too_expensive = not transient and isinstance(error, _TOO_EXPENSIVE_ERRORS)
+ if not transient and not too_expensive:
+ capture_exception(error)
+ cache.set(cache_key, _UNKNOWN, _TOO_EXPENSIVE_CACHE_SECONDS if too_expensive else _FAILED_CACHE_SECONDS)
+ self._stopped = True
+ return None
+ settled = answer or timezone.now() - window.end > _SETTLED_AFTER
+ cache.set(cache_key, answer, _ANSWER_CACHE_SECONDS if settled else _RECENT_NOBODY_CACHE_SECONDS)
+ return answer
+
+ def _cache_key(self, window: _Window) -> str:
+ experiment = self._experiment
+ # Every input of the query. The resolved exposure event is one, because the exposure event rollout
+ # can move an experiment to another event.
+ inputs = json.dumps(
+ [
+ self._launched_at.isoformat(),
+ window.start.isoformat(),
+ window.end.isoformat(),
+ experiment.get_feature_flag_key(),
+ sorted(window.variant_keys),
+ experiment.exposure_criteria,
+ self._default_exposure_event,
+ ],
+ sort_keys=True,
+ default=str,
+ )
+ digest = hashlib.sha256(inputs.encode()).hexdigest()
+ return f"experiment_split_exposure:{experiment.team_id}:{experiment.id}:{digest}"
+
+
+def _load_split_history(
+ experiment: Experiment, reader_access: ExperimentHealthReaderAccess
+) -> SplitHistory | SplitHistoryNotChecked | None:
+ launched_at = experiment.start_date
+ # django-stubs types the id as int, but an unsaved instance can carry None.
+ feature_flag_id: int | None = experiment.feature_flag_id
+ if launched_at is None or experiment.end_date is not None or experiment.archived or feature_flag_id is None:
+ return None
+ if experiment.feature_flag.deleted:
+ return None
+ team_timezone = experiment.team.timezone
+ if not reader_access.can_read_flag_history:
+ return SplitHistoryNotChecked(
+ reason=SplitHistoryNotCheckedReason.NO_HISTORY_ACCESS,
+ launched_at=launched_at,
+ team_timezone=team_timezone,
+ changes=(),
+ )
+
+ changes = tuple(
+ _split_changes_since(team_id=experiment.team_id, feature_flag_id=feature_flag_id, since=launched_at)
+ )
+ if not changes:
+ return SplitHistory(
+ launched_at=launched_at,
+ team_timezone=team_timezone,
+ counted_changes=(),
+ exposed_before_first=False,
+ exposed_between=None,
+ )
+ reason = _not_checked_reason(experiment, reader_access)
+ if reason is not None:
+ return SplitHistoryNotChecked(
+ reason=reason, launched_at=launched_at, team_timezone=team_timezone, changes=changes
+ )
+
+ starts = (launched_at, *(change.changed_at for change in changes[:-1]))
+ walk = [
+ _Window(start=start, end=change.changed_at, variant_keys=split_variant_keys(change.before))
+ for start, change in zip(starts, changes)
+ ]
+ gate = _ExposureGate(experiment, launched_at, prefetch=walk)
+ counted: tuple[SplitChange, ...] = ()
+ exposed_before_first: bool | None = False
+ exposed_between: bool | None = None
+ for index, window in enumerate(walk):
+ exposed_before = gate.exposed(window)
+ if exposed_before is not False:
+ counted = changes[index:]
+ exposed_before_first = exposed_before
+ exposed_between = _exposed_between(gate, counted)
+ break
+
+ return SplitHistory(
+ launched_at=launched_at,
+ team_timezone=team_timezone,
+ counted_changes=counted,
+ exposed_before_first=exposed_before_first,
+ exposed_between=exposed_between,
+ )
+
+
+def _not_checked_reason(
+ experiment: Experiment, reader_access: ExperimentHealthReaderAccess
+) -> SplitHistoryNotCheckedReason | None:
+ # The criteria come first, because adding the query:read scope would not let the check run for them.
+ try:
+ criteria = normalize_to_exposure_criteria(experiment.exposure_criteria)
+ except pydantic.ValidationError:
+ return SplitHistoryNotCheckedReason.EXPOSURE_CRITERIA
+ config = criteria.exposure_config if criteria else None
+ if isinstance(config, ActionsNode):
+ return SplitHistoryNotCheckedReason.EXPOSURE_ACTION
+ if config is not None and config.properties:
+ return SplitHistoryNotCheckedReason.EXPOSURE_FILTERS
+ if not reader_access.can_query_events:
+ return SplitHistoryNotCheckedReason.NO_QUERY_ACCESS
+ return None
+
+
+def _exposed_between(gate: _ExposureGate, counted: Sequence[SplitChange]) -> bool | None:
+ first = counted[0]
+ last = counted[-1]
+ if not same_assignment(first.before, last.after):
+ return None
+ in_between = [change.after for change in counted[:-1]]
+ # A flag without variants serves `true`, so people can be exposed with no variant key to look for.
+ if any(not split_variant_keys(split) for split in in_between):
+ return None
+ variant_keys = tuple(sorted({key for split in in_between for key in split_variant_keys(split)}))
+ return gate.exposed(_Window(start=first.changed_at, end=last.changed_at, variant_keys=variant_keys))
+
+
+def _split_changes_since(*, team_id: int, feature_flag_id: int, since: datetime) -> list[SplitChange]:
+ rows = (
+ ActivityLog.objects.filter(
+ team_id=team_id,
+ scope="FeatureFlag",
+ item_id=str(feature_flag_id),
+ created_at__gt=since,
+ detail__contains={"changes": [{"field": "filters"}]},
+ )
+ .order_by("created_at")
+ # Only the variants decide the split, and the whole `detail` of a flag edit can be large.
+ .annotate(
+ job_type=KT("detail__trigger__job_type"),
+ before_variants=_variants_of_filters_change(_BEFORE_VARIANTS_PATH),
+ after_variants=_variants_of_filters_change(_AFTER_VARIANTS_PATH),
+ )
+ .values_list("created_at", "job_type", "before_variants", "after_variants")
+ )
+ changes = [
+ split_change_from_activity(
+ changed_at=changed_at, job_type=job_type, before_variants=before_variants, after_variants=after_variants
+ )
+ for changed_at, job_type, before_variants, after_variants in rows
+ ]
+ return [change for change in changes if change is not None]
+
+
+def _variants_of_filters_change(path: str) -> Func:
+ return Func(F("detail"), Value(path), function="jsonb_path_query_first", output_field=JSONField())
diff --git a/products/experiments/backend/health/registry.py b/products/experiments/backend/health/registry.py
index f7fbe143f0cb..7b7e88b6cd4b 100644
--- a/products/experiments/backend/health/registry.py
+++ b/products/experiments/backend/health/registry.py
@@ -8,6 +8,7 @@ from products.experiments.backend.health.checks.flag_state import flag_state
from products.experiments.backend.health.checks.flag_variants import flag_variants_mismatch
from products.experiments.backend.health.checks.forced_variant import forced_variant_release_condition
from products.experiments.backend.health.checks.no_metric import no_metric
+from products.experiments.backend.health.checks.split_changed import split_changed_mid_run
from products.experiments.backend.health.checks.srm import srm
from products.experiments.backend.health.checks.zero_exposures import zero_exposures
from products.experiments.backend.health.context import HealthContext
@@ -16,6 +17,7 @@ HealthCheck = Callable[[HealthContext], ExperimentHealthFinding | None]
EXPERIMENT_HEALTH_CHECKS: tuple[HealthCheck, ...] = (
flag_state,
+ split_changed_mid_run,
flag_variants_mismatch,
forced_variant_release_condition,
no_metric,
diff --git a/products/experiments/backend/health/split_changes.py b/products/experiments/backend/health/split_changes.py
new file mode 100644
index 000000000000..bef9a76133a4
--- /dev/null
+++ b/products/experiments/backend/health/split_changes.py
@@ -0,0 +1,157 @@
+"""
+Changes of a flag's variant split, read from the flag's activity log. Pure functions, no I/O.
+
+The flag service draws a variant from a hash, and each variant is a slot of the split in stored order
+(`select_variant` in `rust/feature-flags/src/flags/v1_bucketing.rs`). A changed split moves the slot boundaries,
+so people whose hash lies between an old and a new boundary get another variant. A rollout change, or a
+release-condition change without a variant override, moves people into or out of the flag, never to another
+variant, so only the split counts here.
+"""
+
+from collections import Counter
+from collections.abc import Sequence
+from datetime import datetime
+from enum import StrEnum
+from zoneinfo import ZoneInfo
+
+from posthog.dataclasses import frozen
+
+from products.experiments.backend.health.context import Split, SplitChange, parse_variants
+
+
+class SplitChangeShape(StrEnum):
+ # pinned: the finding's subcodes. The page sends them as `finding_variant` on the health finding events.
+ VARIANT_ROLLED_OUT = "variant_rolled_out"
+ VARIANT_REMOVED = "variant_removed"
+ VARIANT_ADDED = "variant_added"
+ VARIANT_ZEROED = "variant_zeroed"
+ REORDERED = "reordered"
+ REBALANCED = "rebalanced"
+ REVERTED = "reverted"
+
+
+@frozen
+class SplitNetEffect:
+ shape: SplitChangeShape
+ from_split: Split
+ to_split: Split
+ first: SplitChange
+ last: SplitChange
+ change_count: int
+
+
+# Freezing narrows the release conditions to the exposed people, and unfreezing undoes it. Neither changes
+# the split, but both write the whole `filters` value.
+_SKIPPED_JOB_TYPES = frozenset({"experiment_exposure_frozen", "experiment_exposure_unfrozen"})
+
+
+def split_change_from_activity(
+ *, changed_at: datetime, job_type: object, before_variants: object, after_variants: object
+) -> SplitChange | None:
+ """The split change in one activity log row of the flag, or None when the row does not change the split."""
+ if job_type in _SKIPPED_JOB_TYPES:
+ return None
+ before = parse_variants(before_variants)
+ after = parse_variants(after_variants)
+ if same_assignment(before, after):
+ return None
+ return SplitChange(changed_at=changed_at, before=before, after=after)
+
+
+def split_shape(before: Split, after: Split) -> SplitChangeShape:
+ """The shape of a change from one split to another, for two splits that differ. The first match wins."""
+ rolled_out = rolled_out_variant_key(after)
+ # Also a switch of the variant at 100%, so the shipped finding covers it without a second row.
+ if rolled_out is not None and rolled_out != rolled_out_variant_key(before):
+ return SplitChangeShape.VARIANT_ROLLED_OUT
+ # A rename counts as a removal, because the analysis drops the exposures of a key the flag no longer has.
+ if removed_variant_keys(before, after):
+ return SplitChangeShape.VARIANT_REMOVED
+ if added_variant_keys(before, after):
+ return SplitChangeShape.VARIANT_ADDED
+ if zeroed_variant_keys(before, after):
+ return SplitChangeShape.VARIANT_ZEROED
+ if Counter(served_slots(before)) == Counter(served_slots(after)):
+ return SplitChangeShape.REORDERED
+ return SplitChangeShape.REBALANCED
+
+
+def net_effect(changes: Sequence[SplitChange]) -> SplitNetEffect | None:
+ if not changes:
+ return None
+ first = changes[0]
+ last = changes[-1]
+ return SplitNetEffect(
+ shape=(
+ SplitChangeShape.REVERTED
+ if same_assignment(first.before, last.after)
+ else split_shape(first.before, last.after)
+ ),
+ from_split=first.before,
+ to_split=last.after,
+ first=first,
+ last=last,
+ change_count=len(changes),
+ )
+
+
+def served_slots(split: Split) -> Split:
+ # The flag service walks the cumulative percentages in order, so a variant at 0% has no range and serves
+ # nobody. A percentage it can't read counts as served.
+ return tuple(variant for variant in split if variant.rollout_percentage != 0)
+
+
+def same_assignment(before: Split, after: Split) -> bool:
+ """Whether both splits give every person the same variant."""
+ return served_slots(before) == served_slots(after)
+
+
+def rolled_out_variant_key(split: Split) -> str | None:
+ # A holdout is drawn before the split with a hash of its own, so one variant at 100% is a rollout also
+ # when the flag has a holdout.
+ full = [variant for variant in split if variant.rollout_percentage == 100]
+ return full[0].key if len(full) == 1 else None
+
+
+def removed_variant_keys(before: Split, after: Split) -> list[str]:
+ return _keys_missing_from(after, split=served_slots(before))
+
+
+def added_variant_keys(before: Split, after: Split) -> list[str]:
+ return _keys_missing_from(before, split=served_slots(after))
+
+
+def zeroed_variant_keys(before: Split, after: Split) -> list[str]:
+ served_before = {variant.key for variant in served_slots(before)}
+ return [
+ variant.key
+ for variant in after
+ if variant.key and variant.rollout_percentage == 0 and variant.key in served_before
+ ]
+
+
+def split_variant_keys(split: Split) -> tuple[str, ...]:
+ return tuple(variant.key for variant in split if variant.key)
+
+
+def describe_split(split: Split) -> str:
+ """The split as the evidence and the wording show it, for example "control 50% / test 50%"."""
+ if not split:
+ return "no variants"
+ return " / ".join(
+ f"{variant.key or 'unnamed'} {variant.rollout_percentage:g}%"
+ if variant.rollout_percentage is not None
+ else variant.key or "unnamed"
+ for variant in split
+ )
+
+
+def format_change_time(value: datetime, team_timezone: str) -> str:
+ # The format of the alert messages (posthog/tasks/alerts/utils.py). The time matters, because a start
+ # date moved to the change must not keep the hours before it.
+ return value.astimezone(ZoneInfo(team_timezone)).strftime("%B %-d, %Y at %-I:%M %p %Z")
+
+
+def _keys_missing_from(other: Split, *, split: Split) -> list[str]:
+ other_keys = {variant.key for variant in other}
+ return [variant.key for variant in split if variant.key and variant.key not in other_keys]
diff --git a/products/experiments/backend/health/test/test_exposure_gate.py b/products/experiments/backend/health/test/test_exposure_gate.py
new file mode 100644
index 000000000000..f294d1549ca6
--- /dev/null
+++ b/products/experiments/backend/health/test/test_exposure_gate.py
@@ -0,0 +1,402 @@
+from collections.abc import Callable
+from datetime import datetime, timedelta
+from typing import Any
+
+import time_machine
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import ANY, MagicMock, patch
+
+from django.core.cache import cache
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.exceptions import ClickHouseClusterMemoryLimitExceeded, ClickHouseQueryTimeOut
+from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.experiments.backend.facade.contracts import ExperimentHealthReaderAccess
+from products.experiments.backend.health.context import (
+ SplitHistory,
+ SplitHistoryNotChecked,
+ SplitHistoryNotCheckedReason,
+)
+from products.experiments.backend.health.exposure_gate import (
+ MAX_EXPOSURE_QUERIES,
+ load_split_history,
+ query_any_exposure,
+)
+from products.experiments.backend.hogql_queries.exposure_query_logic import DEFAULT_EXPOSURE_EVENT
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+FLAG_KEY = "split-gate"
+FULL_ACCESS = ExperimentHealthReaderAccess(can_read_flag_history=True, can_query_events=True)
+_BY_EVENT_PROPERTY: dict[str, Any] = {
+ "exposure_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "$feature_flag_called",
+ "properties": [{"key": "plan", "value": "pro", "operator": "exact", "type": "event"}],
+ }
+}
+_BY_ACTION: dict[str, Any] = {"exposure_config": {"kind": "ActionsNode", "id": 1}}
+_UNREADABLE: dict[str, Any] = {"exposure_config": {"kind": "ExperimentEventExposureConfig"}}
+
+
+def _split(control: int, test: int) -> list[dict[str, Any]]:
+ return [{"key": "control", "rollout_percentage": control}, {"key": "test", "rollout_percentage": test}]
+
+
+def _filters(variants: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"groups": [{"properties": [], "rollout_percentage": 100}], "multivariate": {"variants": variants}}
+
+
+def _create_running_experiment(
+ team: Team, user: User, *, launched_at: datetime, exposure_criteria: dict[str, Any] | None = None
+) -> Experiment:
+ flag = FeatureFlag.objects.create(team=team, created_by=user, key=FLAG_KEY, filters=_filters(_split(50, 50)))
+ return Experiment.objects.create(
+ team=team,
+ name="Split gate",
+ feature_flag=flag,
+ start_date=launched_at,
+ exposure_criteria=exposure_criteria or {},
+ )
+
+
+class TestLoadSplitHistory(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ self.launched_at = timezone.now() - timedelta(days=30)
+ self.experiment = _create_running_experiment(self.team, self.user, launched_at=self.launched_at)
+
+ def _log_split_changes(
+ self, splits: list[list[dict[str, Any]]], *, first_at: datetime | None = None
+ ) -> list[datetime]:
+ first_at = first_at or self.launched_at + timedelta(days=1)
+ changed_at = [first_at + timedelta(hours=index) for index in range(len(splits) - 1)]
+ for at, before, after in zip(changed_at, splits, splits[1:]):
+ ActivityLog.objects.create(
+ team_id=self.team.id,
+ scope="FeatureFlag",
+ item_id=str(self.experiment.feature_flag_id),
+ activity="updated",
+ detail={
+ "changes": [
+ {
+ "type": "FeatureFlag",
+ "action": "changed",
+ "field": "filters",
+ "before": _filters(before),
+ "after": _filters(after),
+ }
+ ]
+ },
+ created_at=at,
+ )
+ return changed_at
+
+ def _load(
+ self,
+ answers: list[bool | Exception] | Callable[..., bool],
+ *,
+ reader_access: ExperimentHealthReaderAccess = FULL_ACCESS,
+ ) -> tuple[SplitHistory | SplitHistoryNotChecked | None, MagicMock]:
+ with patch(
+ "products.experiments.backend.health.exposure_gate.query_any_exposure", side_effect=answers
+ ) as query:
+ history = load_split_history(self.experiment, reader_access=reader_access)
+ return history, query
+
+ def test_changes_before_the_first_exposure_do_not_count(self) -> None:
+ changed_at = self._log_split_changes([_split(50, 50), _split(60, 40), _split(70, 30), _split(80, 20)])
+
+ history, query = self._load([False, True])
+
+ assert isinstance(history, SplitHistory)
+ self.assertEqual([change.changed_at for change in history.counted_changes], changed_at[1:])
+ self.assertIs(history.exposed_before_first, True)
+ self.assertEqual(
+ [(call.kwargs["window_start"], call.kwargs["window_end"]) for call in query.call_args_list],
+ [(self.launched_at, changed_at[0]), (changed_at[0], changed_at[1])],
+ )
+
+ def test_no_exposure_before_any_change(self) -> None:
+ self._log_split_changes([_split(50, 50), _split(60, 40), _split(70, 30)])
+
+ history, _ = self._load([False, False])
+
+ assert isinstance(history, SplitHistory)
+ self.assertEqual(history.counted_changes, ())
+
+ @parameterized.expand(
+ [
+ ("default_exposure", {}),
+ (
+ "custom_event_without_property_filters",
+ {"exposure_config": {"kind": "ExperimentEventExposureConfig", "event": "checkout", "properties": []}},
+ ),
+ (
+ "activation_event_on_the_default_exposure",
+ {
+ "activation_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "checkout",
+ "properties": [{"key": "plan", "value": "pro", "operator": "exact", "type": "event"}],
+ }
+ },
+ ),
+ ]
+ )
+ def test_criteria_that_name_an_event_are_checked_against_exposures(
+ self, _name: str, exposure_criteria: dict[str, Any]
+ ) -> None:
+ self.experiment.exposure_criteria = exposure_criteria
+ self.experiment.save()
+ self._log_split_changes([_split(50, 50), _split(60, 40)])
+
+ history, query = self._load([True])
+
+ assert isinstance(history, SplitHistory)
+ self.assertIs(history.exposed_before_first, True)
+ self.assertEqual(query.call_count, 1)
+
+ @parameterized.expand(
+ [
+ ("exposure_filters", _BY_EVENT_PROPERTY, True, True, SplitHistoryNotCheckedReason.EXPOSURE_FILTERS),
+ ("exposure_action", _BY_ACTION, True, True, SplitHistoryNotCheckedReason.EXPOSURE_ACTION),
+ ("exposure_criteria", _UNREADABLE, True, True, SplitHistoryNotCheckedReason.EXPOSURE_CRITERIA),
+ ("no_query_access", {}, True, False, SplitHistoryNotCheckedReason.NO_QUERY_ACCESS),
+ (
+ "filters_without_query_access",
+ _BY_EVENT_PROPERTY,
+ True,
+ False,
+ SplitHistoryNotCheckedReason.EXPOSURE_FILTERS,
+ ),
+ ("no_history_access", {}, False, True, SplitHistoryNotCheckedReason.NO_HISTORY_ACCESS),
+ ]
+ )
+ def test_split_changes_that_cannot_be_checked(
+ self,
+ _name: str,
+ exposure_criteria: dict[str, Any],
+ can_read_flag_history: bool,
+ can_query_events: bool,
+ expected_reason: SplitHistoryNotCheckedReason,
+ ) -> None:
+ self.experiment.exposure_criteria = exposure_criteria
+ self.experiment.save()
+ changed_at = self._log_split_changes([_split(50, 50), _split(60, 40), _split(70, 30)])
+
+ history, query = self._load(
+ [True],
+ reader_access=ExperimentHealthReaderAccess(
+ can_read_flag_history=can_read_flag_history, can_query_events=can_query_events
+ ),
+ )
+
+ assert isinstance(history, SplitHistoryNotChecked)
+ self.assertEqual(history.reason, expected_reason)
+ expected_changes = changed_at if can_read_flag_history else []
+ self.assertEqual([change.changed_at for change in history.changes], expected_changes)
+ self.assertEqual(query.call_count, 0)
+
+ @parameterized.expand(
+ [
+ ("exposure_filters", _BY_EVENT_PROPERTY, FULL_ACCESS),
+ ("no_query_access", {}, ExperimentHealthReaderAccess(can_read_flag_history=True, can_query_events=False)),
+ ]
+ )
+ def test_flag_without_split_changes_needs_no_check(
+ self, _name: str, exposure_criteria: dict[str, Any], reader_access: ExperimentHealthReaderAccess
+ ) -> None:
+ self.experiment.exposure_criteria = exposure_criteria
+ self.experiment.save()
+
+ history, _ = self._load([], reader_access=reader_access)
+
+ assert isinstance(history, SplitHistory)
+ self.assertEqual(history.counted_changes, ())
+
+ @parameterized.expand(
+ [
+ ("same_split", _split(50, 50)),
+ ("with_a_variant_left_at_zero", [*_split(50, 50), {"key": "blue", "rollout_percentage": 0}]),
+ ]
+ )
+ def test_revert_asks_whether_anyone_was_exposed_in_between(
+ self, _name: str, set_back_to: list[dict[str, Any]]
+ ) -> None:
+ changed_at = self._log_split_changes([_split(50, 50), _split(0, 100), set_back_to])
+
+ history, query = self._load([True, False])
+
+ assert isinstance(history, SplitHistory)
+ self.assertIs(history.exposed_between, False)
+ self.assertEqual(
+ query.call_args.kwargs,
+ {
+ "window_start": changed_at[0],
+ "window_end": changed_at[1],
+ "variant_keys": ("control", "test"),
+ "default_exposure_event": ANY,
+ },
+ )
+
+ @parameterized.expand(
+ [
+ ("scan_too_expensive", ClickHouseQueryTimeOut(), False, 0),
+ ("transient_memory_pressure", ClickHouseClusterMemoryLimitExceeded(), False, 1),
+ ("unexpected_error", RuntimeError("unexpected"), True, 1),
+ ]
+ )
+ def test_failed_query_counts_the_change_as_unknown_and_is_not_retried_on_the_next_load(
+ self, _name: str, error: Exception, reported: bool, queries_two_hours_later: int
+ ) -> None:
+ changed_at = self._log_split_changes([_split(50, 50), _split(60, 40), _split(70, 30)])
+
+ with patch("products.experiments.backend.health.exposure_gate.capture_exception") as capture:
+ history, _ = self._load([False, error])
+ next_load, next_query = self._load([True])
+
+ assert isinstance(history, SplitHistory) and isinstance(next_load, SplitHistory)
+ self.assertEqual([change.changed_at for change in history.counted_changes], changed_at[1:])
+ self.assertIsNone(history.exposed_before_first)
+ self.assertIsNone(next_load.exposed_before_first)
+ self.assertEqual(next_query.call_count, 0)
+ self.assertEqual(capture.called, reported)
+ with time_machine.travel(timezone.now() + timedelta(hours=2)):
+ _, later_query = self._load([True])
+ self.assertEqual(later_query.call_count, queries_two_hours_later)
+
+ @parameterized.expand(
+ [
+ ("query_limit", 0, MAX_EXPOSURE_QUERIES),
+ ("time_budget", 6, 2),
+ ]
+ )
+ def test_request_limit_counts_the_next_change_as_unknown(
+ self, _name: str, seconds_per_query: float, expected_queries: int
+ ) -> None:
+ changed_at = self._log_split_changes([_split(50, 50), _split(60, 40)] * 11 + [_split(50, 50)])
+ clock = [0.0]
+
+ def nobody_exposed(*_args: Any, **_kwargs: Any) -> bool:
+ clock[0] += seconds_per_query
+ return False
+
+ with patch("products.experiments.backend.health.exposure_gate.monotonic", side_effect=lambda: clock[0]):
+ history, query = self._load(nobody_exposed)
+
+ assert isinstance(history, SplitHistory)
+ self.assertEqual(query.call_count, expected_queries)
+ self.assertEqual(history.counted_changes[0].changed_at, changed_at[expected_queries])
+ self.assertIsNone(history.exposed_before_first)
+
+ def test_cached_walk_reads_the_cache_once(self) -> None:
+ self._log_split_changes([_split(50, 50), _split(60, 40)] * 5)
+ self._load([False] * 9)
+
+ with patch("products.experiments.backend.health.exposure_gate.cache", wraps=cache) as cache_spy:
+ history, query = self._load([])
+
+ assert isinstance(history, SplitHistory)
+ self.assertEqual(history.counted_changes, ())
+ self.assertEqual(query.call_count, 0)
+ self.assertEqual((cache_spy.get_many.call_count, cache_spy.get.call_count), (1, 0))
+
+ @parameterized.expand(
+ [
+ ("exposed", True, timedelta(minutes=10), timedelta(days=2), 0),
+ ("nobody_in_a_settled_window", False, timedelta(hours=2), timedelta(days=2), 0),
+ ("nobody_in_a_recent_window_minutes_later", False, timedelta(minutes=10), timedelta(minutes=1), 0),
+ ("nobody_in_a_recent_window_later", False, timedelta(minutes=10), timedelta(minutes=10), 1),
+ ]
+ )
+ def test_answer_cache(
+ self,
+ _name: str,
+ answer: bool,
+ change_age: timedelta,
+ next_load_after: timedelta,
+ expected_queries: int,
+ ) -> None:
+ self._log_split_changes([_split(50, 50), _split(60, 40)], first_at=timezone.now() - change_age)
+ self._load([answer])
+
+ with time_machine.travel(timezone.now() + next_load_after):
+ _, query = self._load([answer])
+
+ self.assertEqual(query.call_count, expected_queries)
+
+ def test_revert_through_a_flag_without_variants_leaves_in_between_unknown(self) -> None:
+ self._log_split_changes([_split(50, 50), [], _split(50, 50)])
+
+ history, query = self._load([True])
+
+ assert isinstance(history, SplitHistory)
+ self.assertIsNone(history.exposed_between)
+ self.assertEqual(query.call_count, 1)
+
+
+class TestQueryAnyExposure(ClickhouseTestMixin, BaseTest):
+ @parameterized.expand(
+ [
+ ("exposure_before_the_change", None, "$feature_flag_called", "test", 3, True),
+ ("exposure_after_the_change", None, "$feature_flag_called", "test", 0.5, False),
+ ("variant_outside_the_keys", None, "$feature_flag_called", "blue", 3, False),
+ (
+ "custom_exposure_event",
+ {
+ "exposure_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "checkout_viewed",
+ "properties": [],
+ }
+ },
+ "checkout_viewed",
+ "test",
+ 3,
+ True,
+ ),
+ ]
+ )
+ def test_query_any_exposure(
+ self,
+ _name: str,
+ exposure_criteria: dict[str, Any] | None,
+ event: str,
+ variant: str,
+ days_ago: float,
+ expected: bool,
+ ) -> None:
+ now = timezone.now()
+ experiment = _create_running_experiment(
+ self.team, self.user, launched_at=now - timedelta(days=5), exposure_criteria=exposure_criteria
+ )
+ properties = (
+ {"$feature_flag": FLAG_KEY, "$feature_flag_response": variant}
+ if event == "$feature_flag_called"
+ else {f"$feature/{FLAG_KEY}": variant}
+ )
+ _create_event(
+ team=self.team,
+ event=event,
+ distinct_id="person-1",
+ properties=properties,
+ timestamp=now - timedelta(days=days_ago),
+ )
+ flush_persons_and_events()
+
+ exposed = query_any_exposure(
+ experiment,
+ window_start=now - timedelta(days=5),
+ window_end=now - timedelta(days=1),
+ variant_keys=["control", "test"],
+ default_exposure_event=DEFAULT_EXPOSURE_EVENT,
+ )
+
+ self.assertIs(exposed, expected)
diff --git a/products/experiments/backend/health/test/test_flag_state.py b/products/experiments/backend/health/test/test_flag_state.py
index d70d8f08c9d8..ae4b869e2adc 100644
--- a/products/experiments/backend/health/test/test_flag_state.py
+++ b/products/experiments/backend/health/test/test_flag_state.py
@@ -62,6 +62,7 @@ def _context(
primary_metric_count=1,
secondary_metric_count=0,
exposures=None,
+ split_history=None,
)
diff --git a/products/experiments/backend/health/test/test_flag_variants.py b/products/experiments/backend/health/test/test_flag_variants.py
index 4e0a32375167..b9f42c5245a3 100644
--- a/products/experiments/backend/health/test/test_flag_variants.py
+++ b/products/experiments/backend/health/test/test_flag_variants.py
@@ -38,6 +38,7 @@ def _context(
primary_metric_count=1,
secondary_metric_count=0,
exposures=None,
+ split_history=None,
)
diff --git a/products/experiments/backend/health/test/test_forced_variant.py b/products/experiments/backend/health/test/test_forced_variant.py
index e4cc392425ec..b655befac3ea 100644
--- a/products/experiments/backend/health/test/test_forced_variant.py
+++ b/products/experiments/backend/health/test/test_forced_variant.py
@@ -42,6 +42,7 @@ def _context(
primary_metric_count=1,
secondary_metric_count=0,
exposures=None,
+ split_history=None,
)
diff --git a/products/experiments/backend/health/test/test_no_metric.py b/products/experiments/backend/health/test/test_no_metric.py
index d5a9938c3be2..9675317facf3 100644
--- a/products/experiments/backend/health/test/test_no_metric.py
+++ b/products/experiments/backend/health/test/test_no_metric.py
@@ -21,6 +21,7 @@ def _context(**changes: Any) -> HealthContext:
"primary_metric_count": 0,
"secondary_metric_count": 0,
"exposures": None,
+ "split_history": None,
}
return HealthContext(**{**values, **changes})
diff --git a/products/experiments/backend/health/test/test_registry.py b/products/experiments/backend/health/test/test_registry.py
index df92398fade4..c8352a0273eb 100644
--- a/products/experiments/backend/health/test/test_registry.py
+++ b/products/experiments/backend/health/test/test_registry.py
@@ -41,6 +41,7 @@ RUNNING_UNEVEN_SPLIT = HealthContext(
primary_metric_count=1,
secondary_metric_count=0,
exposures=UNEVEN_SPLIT_TOTALS,
+ split_history=None,
)
NO_EXPOSURES = replace(UNEVEN_SPLIT_TOTALS, total_exposures={"control": 0, "test": 0})
diff --git a/products/experiments/backend/health/test/test_split_changed.py b/products/experiments/backend/health/test/test_split_changed.py
new file mode 100644
index 000000000000..66e3dd0ff2ea
--- /dev/null
+++ b/products/experiments/backend/health/test/test_split_changed.py
@@ -0,0 +1,392 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from unittest import TestCase
+
+from parameterized import parameterized
+
+from products.experiments.backend.facade.contracts import (
+ ExperimentHealthFindingActionKind,
+ ExperimentHealthFindingCode,
+ ExperimentHealthFindingSeverity,
+)
+from products.experiments.backend.health.checks.flag_state import flag_state
+from products.experiments.backend.health.checks.split_changed import split_changed_mid_run
+from products.experiments.backend.health.context import (
+ HealthContext,
+ SplitChange,
+ SplitHistory,
+ SplitHistoryNotChecked,
+ SplitHistoryNotCheckedReason,
+ parse_flag_state,
+ parse_variants,
+)
+
+LAUNCHED_AT = datetime(2026, 9, 12, 10, 0, tzinfo=UTC)
+FIRST_CHANGE_AT = datetime(2026, 9, 12, 13, 4, tzinfo=UTC)
+FIRST_CHANGE = "September 12, 2026 at 3:04 PM CEST"
+SECOND_CHANGE = "September 12, 2026 at 3:21 PM CEST"
+THIRD_CHANGE = "September 12, 2026 at 3:38 PM CEST"
+MIXED_ASSIGNMENTS = "A sample ratio mismatch or users in more than one variant can come from this change."
+
+EVERYONE = [{"properties": [], "rollout_percentage": 100}]
+TARGETED = [{"properties": [{"key": "plan", "value": "pro", "type": "person"}], "rollout_percentage": 100}]
+
+RUNNING = {"is_launched": True, "is_running": True, "has_ended": False}
+ENDED = {"is_launched": True, "is_running": False, "has_ended": True}
+
+
+def _split(*variants: tuple[str, float]) -> list[dict[str, Any]]:
+ return [{"key": key, "rollout_percentage": share} for key, share in variants]
+
+
+EVEN = _split(("control", 50), ("test", 50))
+UNEVEN = _split(("control", 80), ("test", 20))
+THREE_WAY = _split(("control", 34), ("test", 33), ("blue", 33))
+BLUE_ZEROED = _split(("control", 50), ("test", 50), ("blue", 0))
+SHIPPED = _split(("control", 0), ("test", 100))
+
+
+def _context(
+ *splits: list[dict[str, Any]],
+ status: dict[str, bool] = RUNNING,
+ groups: list[dict[str, Any]] = EVERYONE,
+ exposed_before_first: bool | None = True,
+ exposed_between: bool | None = None,
+ launched_at: datetime = LAUNCHED_AT,
+ first_change_at: datetime = FIRST_CHANGE_AT,
+ archived: bool = False,
+ deleted: bool = False,
+ not_checked: SplitHistoryNotCheckedReason | None = None,
+) -> HealthContext:
+ changes = tuple(
+ SplitChange(
+ changed_at=first_change_at + timedelta(minutes=17 * index),
+ before=parse_variants(before),
+ after=parse_variants(after),
+ )
+ for index, (before, after) in enumerate(zip(splits, splits[1:]))
+ )
+ return HealthContext(
+ **status,
+ is_paused=False,
+ archived=archived,
+ flag=parse_flag_state(active=True, deleted=deleted, groups=groups, variants=splits[-1]),
+ baseline_variant_key=None,
+ primary_metric_count=1,
+ secondary_metric_count=0,
+ exposures=None,
+ split_history=SplitHistory(
+ launched_at=launched_at,
+ team_timezone="Europe/Berlin",
+ counted_changes=changes,
+ exposed_before_first=exposed_before_first,
+ exposed_between=exposed_between,
+ )
+ if not_checked is None
+ else SplitHistoryNotChecked(
+ reason=not_checked, launched_at=launched_at, team_timezone="Europe/Berlin", changes=changes
+ ),
+ )
+
+
+class TestSplitChangedMidRun(TestCase):
+ @parameterized.expand(
+ [
+ (
+ "rebalanced",
+ _context(EVEN, UNEVEN),
+ ("rebalanced", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f"The split changed from control 50% / test 50% to control 80% / test 20% on {FIRST_CHANGE}. "
+ "People exposed before the change may have switched variants, so the results mix two assignments. "
+ f"Reset the experiment, or move its start date to {FIRST_CHANGE} to analyze only the people exposed "
+ f"after the change. {MIXED_ASSIGNMENTS}",
+ ),
+ (
+ "suggested_start_rounded_up_to_the_next_minute",
+ _context(EVEN, UNEVEN, first_change_at=FIRST_CHANGE_AT + timedelta(seconds=45)),
+ ("rebalanced", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f"The split changed from control 50% / test 50% to control 80% / test 20% on {FIRST_CHANGE}. "
+ "People exposed before the change may have switched variants, so the results mix two assignments. "
+ "Reset the experiment, or move its start date to September 12, 2026 at 3:05 PM CEST to analyze "
+ f"only the people exposed after the change. {MIXED_ASSIGNMENTS}",
+ ),
+ (
+ "rebalanced_with_unknown_exposure",
+ _context(EVEN, UNEVEN, exposed_before_first=None),
+ ("rebalanced", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f"The split changed from control 50% / test 50% to control 80% / test 20% on {FIRST_CHANGE}. "
+ "The change came 3 hours after launch. "
+ "People exposed before the change may have switched variants, so the results mix two assignments. "
+ f"Reset the experiment, or move its start date to {FIRST_CHANGE} to analyze only the people exposed "
+ f"after the change. {MIXED_ASSIGNMENTS}",
+ ),
+ (
+ "variant_removed",
+ _context(THREE_WAY, EVEN),
+ ("variant_removed", ExperimentHealthFindingSeverity.WARNING, "E4"),
+ f'Variant "blue" was removed on {FIRST_CHANGE} (from control 34% / test 33% / blue 33% to '
+ 'control 50% / test 50%). The results leave out people who saw only "blue", and people who had '
+ f'"blue" may now get another variant. Reset the experiment, or move its start date to {FIRST_CHANGE}. '
+ f"{MIXED_ASSIGNMENTS}",
+ ),
+ (
+ "variant_added",
+ _context(EVEN, THREE_WAY),
+ ("variant_added", ExperimentHealthFindingSeverity.WARNING, "E4"),
+ f'Variant "blue" was added on {FIRST_CHANGE} (from control 50% / test 50% to control 34% / '
+ "test 33% / blue 33%). People exposed before the change may have switched variants. Reset the "
+ f"experiment, or move its start date to {FIRST_CHANGE}. {MIXED_ASSIGNMENTS}",
+ ),
+ (
+ "variant_zeroed",
+ _context(THREE_WAY, BLUE_ZEROED),
+ ("variant_zeroed", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f'Variant "blue" was set to 0% on {FIRST_CHANGE} (from control 34% / test 33% / blue 33% to '
+ "control 50% / test 50% / blue 0%). People exposed before the change may have switched variants, "
+ f'and no new users get "blue". Reset the experiment, or move its start date to {FIRST_CHANGE}. '
+ f"{MIXED_ASSIGNMENTS}",
+ ),
+ (
+ "reordered",
+ _context(EVEN, _split(("test", 50), ("control", 50))),
+ ("reordered", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f"The order of the variants changed on {FIRST_CHANGE} (from control 50% / test 50% to test 50% / "
+ "control 50%). The order decides who gets which variant, so people exposed before the change may "
+ f"have switched variants. Reset the experiment, or move its start date to {FIRST_CHANGE}. "
+ f"{MIXED_ASSIGNMENTS}",
+ ),
+ (
+ "variant_rolled_out_inside_targeted_conditions",
+ _context(EVEN, SHIPPED, groups=TARGETED),
+ ("variant_rolled_out", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f'Variant "test" was set to 100% of the split on {FIRST_CHANGE}, while the experiment is still '
+ 'running. From then on, the split assigns everyone to variant "test". End the experiment with a '
+ f"conclusion, or restore the split. {MIXED_ASSIGNMENTS}",
+ ),
+ (
+ "several_changes_days_after_launch",
+ _context(
+ EVEN,
+ _split(("control", 70), ("test", 30)),
+ _split(("control", 60), ("test", 40)),
+ UNEVEN,
+ launched_at=LAUNCHED_AT - timedelta(days=8),
+ ),
+ ("rebalanced", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f"The split changed 3 times between {FIRST_CHANGE} and {THIRD_CHANGE}, from control 50% / "
+ "test 50% to control 80% / test 20%. The first change came 8 days after launch. People exposed "
+ "before the changes may have switched variants, so the results mix two assignments. Reset the "
+ f"experiment, or move its start date to {THIRD_CHANGE} to analyze only the people exposed after the "
+ "changes. A sample ratio mismatch or users in more than one variant can come from these changes.",
+ ),
+ (
+ "reverted_with_exposures_in_between",
+ _context(EVEN, SHIPPED, EVEN, exposed_between=True),
+ ("reverted", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f"The split was set to control 0% / test 100% on {FIRST_CHANGE} and set back to control 50% / "
+ f"test 50% on {SECOND_CHANGE}. People exposed in between may have switched variants. Move the start "
+ f"date to {SECOND_CHANGE}, or reset the experiment.",
+ ),
+ (
+ "reverted_with_unknown_exposures_in_between",
+ _context(EVEN, SHIPPED, EVEN, exposed_between=None),
+ ("reverted", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f"The split was set to control 0% / test 100% on {FIRST_CHANGE} and set back to control 50% / "
+ f"test 50% on {SECOND_CHANGE}. People exposed in between may have switched variants. Move the start "
+ f"date to {SECOND_CHANGE}, or reset the experiment.",
+ ),
+ (
+ "reverted_without_exposures_in_between",
+ _context(EVEN, SHIPPED, EVEN, exposed_between=False),
+ ("reverted", ExperimentHealthFindingSeverity.INFO, "E3"),
+ f"The split was set to control 0% / test 100% on {FIRST_CHANGE} and set back 17 minutes later. "
+ "Nobody was exposed in between.",
+ ),
+ (
+ "reverted_through_a_flag_without_variants",
+ _context(EVEN, [], EVEN, exposed_between=True),
+ ("reverted", ExperimentHealthFindingSeverity.WARNING, "E3"),
+ f"The split was set to no variants on {FIRST_CHANGE} and set back to control 50% / test 50% on "
+ f"{SECOND_CHANGE}. People exposed in between may have switched variants. Move the start date to "
+ f"{SECOND_CHANGE}, or reset the experiment.",
+ ),
+ ]
+ )
+ def test_reports_the_net_change(
+ self,
+ _name: str,
+ ctx: HealthContext,
+ expected: tuple[str, ExperimentHealthFindingSeverity, str],
+ expected_detail: str,
+ ) -> None:
+ finding = split_changed_mid_run(ctx)
+
+ assert finding is not None
+ self.assertEqual(finding.code, ExperimentHealthFindingCode.SPLIT_CHANGED_MID_RUN)
+ self.assertEqual((finding.subcode, finding.severity, finding.diagnostic_ref), expected)
+ self.assertEqual(finding.detail, expected_detail)
+ self.assertEqual(finding.actions, (ExperimentHealthFindingActionKind.OPEN_FEATURE_FLAG_HISTORY,))
+
+ @parameterized.expand(
+ [
+ (
+ "unknown_exposure",
+ _context(EVEN, UNEVEN, exposed_before_first=None),
+ {
+ "change_count": 1,
+ "first_changed_at": "2026-09-12T13:04:00+00:00",
+ "last_changed_at": "2026-09-12T13:04:00+00:00",
+ "from": "control 50% / test 50%",
+ "to": "control 80% / test 20%",
+ "exposed_before_change": None,
+ "seconds_after_launch": 11040,
+ },
+ ),
+ (
+ "not_checked",
+ _context(EVEN, UNEVEN, not_checked=SplitHistoryNotCheckedReason.EXPOSURE_FILTERS),
+ {
+ "reason": "exposure_filters",
+ "change_count": 1,
+ "first_changed_at": "2026-09-12T13:04:00+00:00",
+ "last_changed_at": "2026-09-12T13:04:00+00:00",
+ "from": "control 50% / test 50%",
+ "to": "control 80% / test 20%",
+ "exposed_before_change": None,
+ "seconds_after_launch": 11040,
+ },
+ ),
+ (
+ "not_checked_without_history_access",
+ _context(EVEN, not_checked=SplitHistoryNotCheckedReason.NO_HISTORY_ACCESS),
+ {"reason": "no_history_access"},
+ ),
+ ]
+ )
+ def test_evidence(self, _name: str, ctx: HealthContext, expected: dict[str, Any]) -> None:
+ finding = split_changed_mid_run(ctx)
+
+ assert finding is not None
+ self.assertEqual(finding.evidence, expected)
+
+ @parameterized.expand(
+ [
+ (
+ "exposure_filters",
+ _context(EVEN, UNEVEN, not_checked=SplitHistoryNotCheckedReason.EXPOSURE_FILTERS),
+ f"The variant split changed from control 50% / test 50% to control 80% / test 20% on {FIRST_CHANGE}. "
+ "This check can't tell whether anyone was exposed before the change, because the exposure criteria "
+ "filter by properties. Review the change in the flag history.",
+ ),
+ (
+ "exposure_action_after_several_changes",
+ _context(
+ EVEN,
+ _split(("control", 70), ("test", 30)),
+ UNEVEN,
+ not_checked=SplitHistoryNotCheckedReason.EXPOSURE_ACTION,
+ ),
+ "The variant split changed 2 times after launch, from control 50% / test 50% to control 80% / "
+ f"test 20%, last on {SECOND_CHANGE}. This check can't tell whether anyone was exposed before the "
+ "changes, because exposures come from an action. Review the changes in the flag history.",
+ ),
+ (
+ "exposure_criteria_after_a_split_set_back",
+ _context(EVEN, SHIPPED, EVEN, not_checked=SplitHistoryNotCheckedReason.EXPOSURE_CRITERIA),
+ "The variant split changed 2 times after launch and was set back to control 50% / test 50% on "
+ f"{SECOND_CHANGE}. This check can't tell whether anyone was exposed before the changes, because the "
+ "exposure criteria can't be read. Review the changes in the flag history.",
+ ),
+ (
+ "no_query_access",
+ _context(EVEN, UNEVEN, not_checked=SplitHistoryNotCheckedReason.NO_QUERY_ACCESS),
+ f"The variant split changed from control 50% / test 50% to control 80% / test 20% on {FIRST_CHANGE}. "
+ "This check can't tell whether anyone was exposed before the change, because this API key can't "
+ "query events. Add the query:read scope to this API key, or review the change in the flag history.",
+ ),
+ (
+ "no_history_access",
+ _context(EVEN, not_checked=SplitHistoryNotCheckedReason.NO_HISTORY_ACCESS),
+ "This check can't see whether the variant split changed after launch, because you can't view the "
+ "linked feature flag's history. Viewing the history needs viewer access to the flag and, with an API "
+ "key, the activity_log:read scope.",
+ (),
+ "The variant split history was not checked",
+ ),
+ ]
+ )
+ def test_reports_split_changes_that_were_not_checked(
+ self,
+ _name: str,
+ ctx: HealthContext,
+ expected_detail: str,
+ expected_actions: tuple[ExperimentHealthFindingActionKind, ...] = (
+ ExperimentHealthFindingActionKind.OPEN_FEATURE_FLAG_HISTORY,
+ ),
+ expected_title: str = "Variant split changes were not checked",
+ ) -> None:
+ finding = split_changed_mid_run(ctx)
+
+ assert finding is not None
+ self.assertEqual(
+ (finding.code, finding.subcode, finding.severity, finding.diagnostic_ref, finding.title),
+ (
+ ExperimentHealthFindingCode.SPLIT_CHANGED_MID_RUN,
+ "not_checked",
+ ExperimentHealthFindingSeverity.INFO,
+ "E3",
+ expected_title,
+ ),
+ )
+ self.assertEqual(finding.detail, expected_detail)
+ self.assertEqual(finding.actions, expected_actions)
+
+ @parameterized.expand(
+ [
+ ("ended", _context(EVEN, UNEVEN, status=ENDED)),
+ ("archived", _context(EVEN, UNEVEN, archived=True)),
+ ("deleted_flag", _context(EVEN, UNEVEN, deleted=True)),
+ ("nobody_exposed_before_any_change", _context(EVEN)),
+ ("flag_without_variants_reported_by_flag_variants_mismatch", _context(EVEN, [])),
+ (
+ "not_checked_on_an_ended_experiment",
+ _context(EVEN, status=ENDED, not_checked=SplitHistoryNotCheckedReason.NO_HISTORY_ACCESS),
+ ),
+ ]
+ )
+ def test_no_finding(self, _name: str, ctx: HealthContext) -> None:
+ self.assertIsNone(split_changed_mid_run(ctx))
+
+ @parameterized.expand(
+ [
+ ("one_change", _context(EVEN, SHIPPED), FIRST_CHANGE, "control 50% / test 50%"),
+ (
+ "rollout_after_a_rebalance",
+ _context(EVEN, _split(("control", 70), ("test", 30)), SHIPPED),
+ SECOND_CHANGE,
+ "control 70% / test 30%",
+ ),
+ (
+ "rollout_not_checked",
+ _context(EVEN, SHIPPED, not_checked=SplitHistoryNotCheckedReason.EXPOSURE_FILTERS),
+ FIRST_CHANGE,
+ "control 50% / test 50%",
+ ),
+ ]
+ )
+ def test_shipped_finding_reports_a_rollout_to_everyone(
+ self, _name: str, ctx: HealthContext, rolled_out_at: str, split_before: str
+ ) -> None:
+ shipped = flag_state(ctx)
+
+ self.assertIsNone(split_changed_mid_run(ctx))
+ assert shipped is not None
+ self.assertEqual(shipped.code, ExperimentHealthFindingCode.VARIANT_SHIPPED_WHILE_RUNNING)
+ self.assertEqual(
+ shipped.detail,
+ f'Variant "test" is rolled out to 100% of users. It has been at 100% since {rolled_out_at}, and the '
+ f"split was {split_before} before. The experiment is not comparing variants. End the experiment "
+ "with a conclusion, or adjust the variant distribution of the linked feature flag to resume proper A/B "
+ "testing.",
+ )
diff --git a/products/experiments/backend/health/test/test_split_changes.py b/products/experiments/backend/health/test/test_split_changes.py
new file mode 100644
index 000000000000..c6e8d8201ed2
--- /dev/null
+++ b/products/experiments/backend/health/test/test_split_changes.py
@@ -0,0 +1,150 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from unittest import TestCase
+
+from parameterized import parameterized
+
+from products.experiments.backend.health.context import SplitChange
+from products.experiments.backend.health.split_changes import (
+ SplitChangeShape,
+ net_effect,
+ split_change_from_activity,
+ split_shape,
+)
+
+CHANGED_AT = datetime(2026, 9, 12, 13, 4, tzinfo=UTC)
+
+
+def _split(*variants: tuple[str | None, Any]) -> list[dict[str, Any]]:
+ return [{"key": key, "rollout_percentage": share} for key, share in variants]
+
+
+def _row(before: Any, after: Any, *, job_type: str | None = None) -> dict[str, Any]:
+ return {"job_type": job_type, "before_variants": before, "after_variants": after}
+
+
+EVEN = _split(("control", 50), ("test", 50))
+THREE_WAY = _split(("control", 34), ("test", 33), ("blue", 33))
+BLUE_AT_ZERO = _split(("control", 50), ("test", 50), ("blue", 0))
+
+
+class TestSplitChanges(TestCase):
+ @parameterized.expand(
+ [
+ ("rebalanced", _row(EVEN, _split(("control", 80), ("test", 20))), SplitChangeShape.REBALANCED),
+ ("reordered", _row(EVEN, _split(("test", 50), ("control", 50))), SplitChangeShape.REORDERED),
+ ("variant_added", _row(EVEN, THREE_WAY), SplitChangeShape.VARIANT_ADDED),
+ ("variant_removed", _row(THREE_WAY, EVEN), SplitChangeShape.VARIANT_REMOVED),
+ ("renamed", _row(EVEN, _split(("control", 50), ("treatment", 50))), SplitChangeShape.VARIANT_REMOVED),
+ (
+ "variant_zeroed",
+ _row(THREE_WAY, _split(("control", 50), ("test", 50), ("blue", 0))),
+ SplitChangeShape.VARIANT_ZEROED,
+ ),
+ (
+ "rolled_out_wins_over_zeroed",
+ _row(EVEN, _split(("control", 0), ("test", 100))),
+ SplitChangeShape.VARIANT_ROLLED_OUT,
+ ),
+ (
+ "variant_at_100_switched",
+ _row(_split(("control", 100), ("test", 0)), _split(("control", 0), ("test", 100))),
+ SplitChangeShape.VARIANT_ROLLED_OUT,
+ ),
+ ("integer_against_float", _row(EVEN, _split(("control", 50.0), ("test", 50.0))), None),
+ (
+ "display_name_only",
+ _row(
+ EVEN,
+ [
+ {"key": "control", "name": "Control", "rollout_percentage": 50},
+ {"key": "test", "name": "New checkout", "rollout_percentage": 50},
+ ],
+ ),
+ None,
+ ),
+ (
+ "exposure_freeze",
+ _row(EVEN, _split(("control", 80), ("test", 20)), job_type="experiment_exposure_frozen"),
+ None,
+ ),
+ ("variant_added_at_zero", _row(EVEN, BLUE_AT_ZERO), None),
+ ("variant_at_zero_removed", _row(BLUE_AT_ZERO, EVEN), None),
+ (
+ "variant_at_zero_renamed",
+ _row(BLUE_AT_ZERO, _split(("control", 50), ("test", 50), ("green", 0))),
+ None,
+ ),
+ (
+ "variant_at_zero_moved",
+ _row(_split(("control", 50), ("blue", 0), ("test", 50)), BLUE_AT_ZERO),
+ None,
+ ),
+ ("variant_raised_from_zero", _row(BLUE_AT_ZERO, THREE_WAY), SplitChangeShape.REBALANCED),
+ (
+ "served_variant_swapped_for_one_at_zero",
+ _row(_split(("control", 50), ("test", 0), ("blue", 50)), BLUE_AT_ZERO),
+ SplitChangeShape.VARIANT_ZEROED,
+ ),
+ (
+ "variant_added_at_zero_with_a_rebalance",
+ _row(EVEN, _split(("control", 80), ("test", 20), ("blue", 0))),
+ SplitChangeShape.REBALANCED,
+ ),
+ (
+ "variant_without_key_zeroed",
+ _row(
+ _split(("control", 34), ("test", 33), (None, 33)),
+ _split(("control", 50), ("test", 50), (None, 0)),
+ ),
+ SplitChangeShape.REBALANCED,
+ ),
+ ("no_variants_on_either_side", _row(None, None), None),
+ ]
+ )
+ def test_split_change_from_activity(
+ self, _name: str, row: dict[str, Any], expected_shape: SplitChangeShape | None
+ ) -> None:
+ change = split_change_from_activity(changed_at=CHANGED_AT, **row)
+
+ if expected_shape is None:
+ self.assertIsNone(change)
+ return
+ assert change is not None
+ self.assertEqual(split_shape(change.before, change.after), expected_shape)
+
+ @parameterized.expand(
+ [
+ (
+ "net_effect_of_a_sequence",
+ [EVEN, _split(("control", 70), ("test", 30)), THREE_WAY],
+ SplitChangeShape.VARIANT_ADDED,
+ ),
+ ("set_back", [EVEN, _split(("control", 0), ("test", 100)), EVEN], SplitChangeShape.REVERTED),
+ (
+ "set_back_with_a_variant_left_at_zero",
+ [EVEN, _split(("control", 80), ("test", 20)), BLUE_AT_ZERO],
+ SplitChangeShape.REVERTED,
+ ),
+ ]
+ )
+ def test_net_effect(
+ self, _name: str, sequence: list[list[dict[str, Any]]], expected_shape: SplitChangeShape
+ ) -> None:
+ changes = tuple(
+ _split_change(before, after, CHANGED_AT + timedelta(hours=index))
+ for index, (before, after) in enumerate(zip(sequence, sequence[1:]))
+ )
+
+ effect = net_effect(changes)
+
+ assert effect is not None
+ self.assertEqual((effect.shape, effect.change_count), (expected_shape, len(sequence) - 1))
+ self.assertEqual((effect.from_split, effect.to_split), (changes[0].before, changes[-1].after))
+
+
+def _split_change(before: list[dict[str, Any]], after: list[dict[str, Any]], changed_at: datetime) -> SplitChange:
+ change = split_change_from_activity(changed_at=changed_at, **_row(before, after))
+ assert change is not None
+ return change
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index f9ac11e8afe9..949761c34339 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -189,7 +189,10 @@ class ExperimentMetricDefinitionField(serializers.JSONField):
@extend_schema_field(
{
"type": "object",
- "additionalProperties": {"oneOf": [{"type": "string"}, {"type": "number"}], "nullable": True},
+ "additionalProperties": {
+ "oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}],
+ "nullable": True,
+ },
}
)
class ExperimentHealthEvidenceField(serializers.DictField):
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 8db554f2a8da..145f92d8a466 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -43,7 +43,12 @@ from posthog.models.activity_logging.activity_page import ActivityLogPaginatedRe
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
-from posthog.permissions import get_authenticator_scoped_team_ids, is_service_auth, posthog_feature_flag_enabled
+from posthog.permissions import (
+ get_authenticator_scoped_team_ids,
+ get_authenticator_scopes,
+ is_service_auth,
+ posthog_feature_flag_enabled,
+)
from posthog.rate_limit import (
ClickHouseBurstRateThrottle,
ClickHouseSustainedRateThrottle,
@@ -56,6 +61,7 @@ from posthog.rate_limit import (
SessionEventDeltasBurstRateThrottle,
SessionEventDeltasSustainedRateThrottle,
)
+from posthog.scopes import scopes_not_covered
from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.temporal.common.client import sync_connect
from posthog.temporal.experiments.models import ExperimentTimeseriesRecalculationWorkflowInputs
@@ -69,6 +75,7 @@ from products.access_control.backend.presentation.access_control import AccessCo
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.contracts import ExperimentHealthReaderAccess
from products.experiments.backend.facade.legacy_migration import (
LegacyMigrationError,
migrate_experiment as migrate_legacy_experiment,
@@ -901,13 +908,41 @@ class EnterpriseExperimentsViewSet(
Health check findings for this experiment: problems in its configuration and its feature flag
that keep it from producing trustworthy results, each with a fix.
- The checks here read the experiment, its flag and its linked metrics. The checks that read
- exposures come with the exposure query.
+ The checks here read the experiment, its flag, its linked metrics, and the changes of the
+ flag's variant split since launch. The checks that read exposure counts come with the
+ exposure query. The split-change check compares the split changes with the exposures only
+ for exposure criteria that name an event without property filters. When the split changed
+ after launch and the criteria have filters or an action, or an API key lacks `query:read`,
+ it returns an info finding with the subcode `not_checked` and the cause in
+ `evidence.reason`. A caller who can't view the linked flag's history (viewer access to the
+ flag and, with an API key, `activity_log:read`) gets that finding for every running
+ experiment, because the changes are not read.
"""
experiment: Experiment = self.get_object()
- findings = get_experiment_health_findings(team_id=self.team_id, experiment_id=experiment.id)
+ findings = get_experiment_health_findings(
+ team_id=self.team_id,
+ experiment_id=experiment.id,
+ reader_access=self._health_reader_access(request, experiment),
+ )
return Response(ExperimentHealthSerializer({"findings": findings}).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`.
+ scopes = get_authenticator_scopes(request.successful_authenticator)
+ missing_scopes = (
+ set()
+ if scopes is None or "*" in scopes
+ else set(scopes_not_covered(scopes, ["activity_log:read", "query:read"]))
+ )
+ can_view_flag = experiment.feature_flag_id is None or self.user_access_control.check_access_level_for_object(
+ experiment.feature_flag, required_level="viewer"
+ )
+ return ExperimentHealthReaderAccess(
+ can_read_flag_history=bool(can_view_flag) and "activity_log:read" not in missing_scopes,
+ can_query_events="query:read" not in missing_scopes,
+ )
+
@validated_request(
query_serializer=ExperimentActivityQuerySerializer,
responses={
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 9331aea5c5b3..b1eb84563ac9 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -3905,7 +3905,7 @@ class TestExperimentService(APIBaseTest):
"launch_endpoint",
lambda self: self._create_launchable_experiment(name="Path L", feature_flag_key="path-launch-flag"),
lambda service, experiment, request: service.launch_experiment(experiment, request=request),
- [("launch_endpoint", 0, [], [])],
+ [("launch_endpoint", 0, [], [], [])],
),
(
"launch_endpoint_with_a_qa_override",
@@ -3919,6 +3919,7 @@ class TestExperimentService(APIBaseTest):
0,
["forced_variant_release_condition"],
["forced_variant_release_condition:some_conditions_pinned"],
+ ["forced_variant_release_condition:some_conditions_pinned:info:"],
)
],
),
@@ -3928,7 +3929,7 @@ class TestExperimentService(APIBaseTest):
timedelta(days=3, hours=2), name="Path O", feature_flag_key="path-older-flag"
),
lambda service, experiment, request: service.launch_experiment(experiment, request=request),
- [("launch_endpoint", 266400, [], [])],
+ [("launch_endpoint", 266400, [], [], [])],
),
(
"create_with_start_date",
@@ -3939,7 +3940,7 @@ class TestExperimentService(APIBaseTest):
start_date=timezone.now(),
event_source=EventSource.API,
),
- [("create_request", 0, ["no_metric"], [])],
+ [("create_request", 0, ["no_metric"], [], ["no_metric::warning:"])],
),
(
"create_draft",
@@ -3955,7 +3956,7 @@ class TestExperimentService(APIBaseTest):
lambda service, experiment, request: service.update_experiment(
experiment, {"start_date": timezone.now()}, event_source=EventSource.API
),
- [("update_start_date", 0, [], [])],
+ [("update_start_date", 0, [], [], [])],
),
(
"update_moves_start_date_of_running",
@@ -3985,6 +3986,7 @@ class TestExperimentService(APIBaseTest):
event["flag_age_seconds"],
event["health_finding_codes"],
event["health_finding_subcodes"],
+ event["health_findings"],
)
for event in launched
] == expected
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 6319dfb1abc0..1ca75f78e83a 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -721,6 +721,14 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
None,
[_HEALTH_PAUSED, ("flag_variants_mismatch", "no_control_variant")],
),
+ (
+ "split_edited_after_launch",
+ {"metrics": [_HEALTH_METRIC]},
+ None,
+ [_HEALTH_PAUSED, ("split_changed_mid_run", "rebalanced")],
+ timedelta(days=1),
+ ),
+ ("split_edited_before_launch", {"metrics": [_HEALTH_METRIC]}, None, [_HEALTH_PAUSED], -timedelta(days=1)),
]
)
def test_health_reports_findings(
@@ -729,26 +737,29 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
experiment_fields: dict[str, Any],
shared_metric_link: dict[str, Any] | None,
expected: list[tuple[str, str | None]],
+ split_edit_from_launch: timedelta | None = None,
) -> None:
+ start_date = timezone.now() - timedelta(days=3)
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key=f"health-findings-{_name}",
+ created_by=self.user,
+ active=False,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
experiment = Experiment.objects.create(
team=self.team,
name="health-findings",
- feature_flag=FeatureFlag.objects.create(
- team=self.team,
- key=f"health-findings-{_name}",
- created_by=self.user,
- active=False,
- filters={
- "groups": [{"properties": [], "rollout_percentage": 100}],
- "multivariate": {
- "variants": [
- {"key": "control", "rollout_percentage": 50},
- {"key": "test", "rollout_percentage": 50},
- ]
- },
- },
- ),
- start_date=timezone.now() - timedelta(days=3),
+ feature_flag=flag,
+ start_date=start_date,
metrics=experiment_fields.get("metrics", []),
metrics_secondary=experiment_fields.get("metrics_secondary", []),
stats_config=experiment_fields.get("stats_config", {}),
@@ -770,8 +781,11 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
format="json",
)
self.assertEqual(link_response.status_code, status.HTTP_200_OK, link_response.json())
+ if split_edit_from_launch is not None:
+ self._rebalance_split_at(flag, start_date + split_edit_from_launch)
- response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment.id}/health/")
+ with patch("products.experiments.backend.health.exposure_gate.query_any_exposure", return_value=True):
+ response = self.client.get(f"/api/projects/{self.team.id}/experiments/{experiment.id}/health/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
health = response.json()
@@ -779,6 +793,94 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
self.assertEqual(health["findings"][0]["actions"], ["open_feature_flag"])
self.assertEqual(health["findings"][0]["diagnostic_ref"], "A5")
+ @parameterized.expand(
+ [
+ ("session", None, False, ("rebalanced", None)),
+ ("session_without_flag_access", None, True, ("not_checked", "no_history_access")),
+ (
+ "token_without_query_scope",
+ ["experiment:read", "activity_log:read"],
+ False,
+ ("not_checked", "no_query_access"),
+ ),
+ (
+ "token_without_activity_scope",
+ ["experiment:read", "query:read"],
+ False,
+ ("not_checked", "no_history_access"),
+ ),
+ (
+ "token_with_query_and_activity_scopes",
+ ["experiment:read", "query:read", "activity_log:read"],
+ False,
+ ("rebalanced", None),
+ ),
+ ]
+ )
+ def test_health_checks_the_split_history_only_with_flag_and_query_access(
+ self,
+ _name: str,
+ token_scopes: list[str] | None,
+ restrict_flag: bool,
+ expected_split_finding: tuple[str, str | None],
+ ) -> None:
+ start_date = timezone.now() - timedelta(days=3)
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key=f"health-split-access-{_name}",
+ created_by=self.user,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ experiment = Experiment.objects.create(
+ team=self.team, name="health-split-access", feature_flag=flag, start_date=start_date
+ )
+ self._rebalance_split_at(flag, start_date + timedelta(days=1))
+ headers: dict[str, str] = {}
+ if restrict_flag:
+ self._enable_access_control()
+ self._restrict_flag_and_login_as_member(flag.key, f"health-{_name}@posthog.com")
+ 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.exposure_gate.query_any_exposure", return_value=True):
+ 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)
+ split_findings = [
+ (finding["subcode"], finding["evidence"].get("reason"))
+ for finding in response.json()["findings"]
+ if finding["code"] == "split_changed_mid_run"
+ ]
+ self.assertEqual(split_findings, [expected_split_finding])
+
+ def _rebalance_split_at(self, flag: FeatureFlag, at: datetime) -> None:
+ with time_machine.travel(at), self.captureOnCommitCallbacks(execute=True):
+ flag.filters = {
+ **flag.filters,
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 80},
+ {"key": "test", "rollout_percentage": 20},
+ ]
+ },
+ }
+ flag.save()
+
@parameterized.expand(
[("after_cutoff", 30, "$experiment_exposure"), ("before_cutoff", -30, "$feature_flag_called")]
)
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 183ddb320c6c..f5e33a07ff79 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2272,6 +2272,7 @@ export type _ExperimentApiMetricsListApi = ExperimentApiMetricApi[]
* * `zero_exposures` - Zero Exposures
* * `forced_variant_release_condition` - Forced Variant Release Condition
* * `flag_variants_mismatch` - Flag Variants Mismatch
+ * * `split_changed_mid_run` - Split Changed Mid Run
*/
export type ExperimentHealthFindingCodeEnumApi =
(typeof ExperimentHealthFindingCodeEnumApi)[keyof typeof ExperimentHealthFindingCodeEnumApi]
@@ -2287,6 +2288,7 @@ export const ExperimentHealthFindingCodeEnumApi = {
ZeroExposures: 'zero_exposures',
ForcedVariantReleaseCondition: 'forced_variant_release_condition',
FlagVariantsMismatch: 'flag_variants_mismatch',
+ SplitChangedMidRun: 'split_changed_mid_run',
} as const
/**
@@ -2305,6 +2307,7 @@ export const ExperimentHealthFindingSeverityEnumApi = {
/**
* * `open_feature_flag` - Open Feature Flag
+ * * `open_feature_flag_history` - Open Feature Flag History
* * `adjust_distribution` - Adjust Distribution
* * `use_first_seen_variant` - Use First Seen Variant
* * `add_primary_metric` - Add Primary Metric
@@ -2317,6 +2320,7 @@ export type ExperimentHealthFindingActionKindEnumApi =
export const ExperimentHealthFindingActionKindEnumApi = {
OpenFeatureFlag: 'open_feature_flag',
+ OpenFeatureFlagHistory: 'open_feature_flag_history',
AdjustDistribution: 'adjust_distribution',
UseFirstSeenVariant: 'use_first_seen_variant',
AddPrimaryMetric: 'add_primary_metric',
@@ -2328,7 +2332,7 @@ export const ExperimentHealthFindingActionKindEnumApi = {
/**
* The values behind the finding, such as the key of a shipped variant or the share of users exposed to multiple variants. The keys depend on the code.
*/
-export type ExperimentHealthFindingApiEvidence = { [key: string]: string | number | null }
+export type ExperimentHealthFindingApiEvidence = { [key: string]: string | number | boolean | null }
export interface ExperimentHealthFindingApi {
/** Stable identifier of the problem. Each code has one meaning across every surface that reports it.
@@ -2342,7 +2346,8 @@ export interface ExperimentHealthFindingApi {
* * `srm` - Sample Ratio Mismatch
* * `zero_exposures` - Zero Exposures
* * `forced_variant_release_condition` - Forced Variant Release Condition
- * * `flag_variants_mismatch` - Flag Variants Mismatch */
+ * * `flag_variants_mismatch` - Flag Variants Mismatch
+ * * `split_changed_mid_run` - Split Changed Mid Run */
code: ExperimentHealthFindingCodeEnumApi
/**
* The case within the code, when a code covers several, for example 'running_but_no_rollout' within 'flag_off_while_running'. Null when the code has one case.
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index d25b461b0a64..6ddad5ebcb72 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -700,8 +700,15 @@ export const getExperimentsHealthRetrieveUrl = (projectId: string, id: number) =
* Health check findings for this experiment: problems in its configuration and its feature flag
* that keep it from producing trustworthy results, each with a fix.
*
- * The checks here read the experiment, its flag and its linked metrics. The checks that read
- * exposures come with the exposure query.
+ * The checks here read the experiment, its flag, its linked metrics, and the changes of the
+ * flag's variant split since launch. The checks that read exposure counts come with the
+ * exposure query. The split-change check compares the split changes with the exposures only
+ * for exposure criteria that name an event without property filters. When the split changed
+ * after launch and the criteria have filters or an action, or an API key lacks `query:read`,
+ * it returns an info finding with the subcode `not_checked` and the cause in
+ * `evidence.reason`. A caller who can't view the linked flag's history (viewer access to the
+ * flag and, with an API key, `activity_log:read`) gets that finding for every running
+ * experiment, because the changes are not read.
*/
export const experimentsHealthRetrieve = async (
projectId: string,
diff --git a/products/experiments/frontend/health/HealthFindingActionButton.tsx b/products/experiments/frontend/health/HealthFindingActionButton.tsx
index a00a34f407a3..c3356b603f58 100644
--- a/products/experiments/frontend/health/HealthFindingActionButton.tsx
+++ b/products/experiments/frontend/health/HealthFindingActionButton.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { combineUrl } from 'kea-router'
import { LemonButton } from '@posthog/lemon-ui'
@@ -6,6 +7,7 @@ import { userHasAccess } from 'lib/utils/accessControlUtils'
import { experimentLogic } from 'scenes/experiments/experimentLogic'
import { exposureCriteriaModalLogic } from 'scenes/experiments/ExperimentView/exposureCriteriaModalLogic'
import { modalsLogic } from 'scenes/experiments/modalsLogic'
+import { FeatureFlagsTab } from 'scenes/feature-flags/featureFlagsLogic'
import { urls } from 'scenes/urls'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
@@ -37,7 +39,7 @@ export function HealthFindingActionButton({
// pinned: `data-attr` value, so renaming it breaks autocapture insights
'data-attr': `experiment-health-action-${actionKind}`,
} as const
- // Every action except the flag link opens a form that saves the experiment.
+ // Every action except the flag links opens a form that saves the experiment.
const editProps = {
...buttonProps,
disabledReason: canEdit ? null : "You don't have permission to edit this experiment.",
@@ -55,6 +57,17 @@ export function HealthFindingActionButton({
Open feature flag
</LemonButton>
) : null
+ case 'open_feature_flag_history':
+ return experiment.feature_flag ? (
+ <LemonButton
+ {...buttonProps}
+ to={combineUrl(urls.featureFlag(experiment.feature_flag.id), { tab: FeatureFlagsTab.HISTORY }).url}
+ targetBlank
+ onClick={onClick}
+ >
+ View flag history
+ </LemonButton>
+ ) : null
case 'adjust_distribution':
return (
<LemonButton
diff --git a/products/experiments/frontend/health/HealthFindingRow.tsx b/products/experiments/frontend/health/HealthFindingRow.tsx
index 2ed642a7c16c..8467fa0eca87 100644
--- a/products/experiments/frontend/health/HealthFindingRow.tsx
+++ b/products/experiments/frontend/health/HealthFindingRow.tsx
@@ -5,6 +5,7 @@ import { LemonButton } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
+import { healthFindingReason } from './experimentHealthFindingEvents'
import { HealthFindingActionButton } from './HealthFindingActionButton'
import type { HealthPanelFinding } from './healthPanelFindings'
import { useHealthFindingReporting } from './useHealthFindingReporting'
@@ -15,6 +16,8 @@ export function HealthFindingRow({ finding }: { finding: HealthPanelFinding }):
const { reportOpened, reportActedOn } = useHealthFindingReporting({
code: finding.code,
variant: finding.subcode ?? undefined,
+ severity: finding.severity,
+ reason: healthFindingReason(finding.evidence),
})
return (
diff --git a/products/experiments/frontend/health/experimentHealthFindingEvents.ts b/products/experiments/frontend/health/experimentHealthFindingEvents.ts
index 268126f3348c..f30bcbb3b743 100644
--- a/products/experiments/frontend/health/experimentHealthFindingEvents.ts
+++ b/products/experiments/frontend/health/experimentHealthFindingEvents.ts
@@ -8,7 +8,7 @@ import type { Experiment } from '~/types'
import { EXPERIMENT_VARIANT_MULTIPLE } from '../constants'
import { getExperimentStatus } from '../experimentStatus'
-import type { ExperimentHealthApi } from '../generated/api.schemas'
+import type { ExperimentHealthApi, ExperimentHealthFindingApi } from '../generated/api.schemas'
import { getTotalExposures, hasSampleRatioMismatch } from './exposureHealth'
// pinned: `finding_code` property values. Insights group and filter on them, so a rename breaks those insights.
@@ -23,11 +23,15 @@ export type ExperimentHealthFindingCode =
| 'no_metric'
| 'forced_variant_release_condition'
| 'flag_variants_mismatch'
+ | 'split_changed_mid_run'
export interface ExperimentHealthFinding {
code: ExperimentHealthFindingCode
/** The sub-case of the code, for example the warning key. It must not hold customer text. */
variant?: string
+ /** Set for a server finding. The separate warnings have none. */
+ severity?: ExperimentHealthFindingApi['severity']
+ reason?: string
}
// pinned: `open_kind` property values, for the same reason as the codes above.
@@ -38,6 +42,7 @@ export type ExperimentHealthFindingActionKind =
| 'adjust_distribution'
| 'use_first_seen_variant'
| 'open_feature_flag'
+ | 'open_feature_flag_history'
| 'edit_exposure_criteria'
| 'edit_release_conditions'
| 'add_primary_metric'
@@ -101,6 +106,8 @@ function healthFindingEventProperties(
experiment_days_since_start: experiment.start_date ? dayjs().diff(experiment.start_date, 'day') : null,
finding_code: finding.code,
finding_variant: finding.variant ?? null,
+ finding_severity: finding.severity ?? null,
+ finding_reason: finding.reason ?? null,
health_ui: healthUi,
surface: 'experiment_page',
// The value the backend reports for a request from the web app, so one breakdown covers both.
@@ -108,6 +115,16 @@ function healthFindingEventProperties(
}
}
+export function healthFindingReason(evidence: ExperimentHealthFindingApi['evidence']): string | undefined {
+ return typeof evidence.reason === 'string' ? evidence.reason : undefined
+}
+
+function trackedHealthFinding({ code, subcode, severity, evidence }: ExperimentHealthFindingApi): string {
+ // pinned: `code:subcode:severity:reason`, as on the server's `experiment launched`. Insights split each string
+ // on `:`, so every field is present, empty when the finding has none.
+ return [code, subcode ?? '', severity, healthFindingReason(evidence) ?? ''].join(':')
+}
+
export function captureExperimentHealthFindingShown(
experiment: Experiment,
finding: ExperimentHealthFinding,
@@ -175,6 +192,7 @@ export function captureExperimentHealthChecked(
// unambiguous when two codes use the same subcode.
health_finding_subcodes:
findings?.flatMap(({ code, subcode }) => (subcode ? [`${code}:${subcode}`] : [])) ?? null,
+ health_findings: findings?.map(trackedHealthFinding) ?? null,
health_finding_count: findings?.length ?? null,
flag_state_browser: browserWarning?.key ?? null,
// The server sends the warning key as the subcode. A finding without one still differs from no finding.
diff --git a/products/experiments/frontend/health/healthDebugReport.ts b/products/experiments/frontend/health/healthDebugReport.ts
index 1f2a1f33003a..576a9b264f3c 100644
--- a/products/experiments/frontend/health/healthDebugReport.ts
+++ b/products/experiments/frontend/health/healthDebugReport.ts
@@ -154,6 +154,30 @@ function forcedVariantChecks(input: HealthDebugInput): HealthDebugCheck[] {
]
}
+function splitChangedChecks(input: HealthDebugInput): HealthDebugCheck[] {
+ const finding = input.health?.findings.find(({ code }) => code === 'split_changed_mid_run')
+ return [
+ {
+ check: 'split_changed_mid_run',
+ source: 'server',
+ result: serverResult(input.health, (code) => code === 'split_changed_mid_run'),
+ note: finding ? splitChangedNote(finding) : null,
+ differs: false,
+ },
+ ]
+}
+
+function splitChangedNote(finding: ExperimentHealthFindingApi): string {
+ const { evidence } = finding
+ if (finding.subcode === 'not_checked') {
+ return evidence.change_count == null
+ ? `Not checked: ${evidence.reason}.`
+ : `Not checked: ${evidence.reason}. ${evidence.change_count} changes since launch, from ${evidence.from} to ${evidence.to}.`
+ }
+ const exposedBefore = evidence.exposed_before_change
+ return `${evidence.change_count} counted changes, from ${evidence.from} to ${evidence.to}. Exposed before the first: ${exposedBefore == null ? 'unknown' : exposedBefore ? 'yes' : 'no'}.`
+}
+
function exposureChecks(input: HealthDebugInput): HealthDebugCheck[] {
const { exposures } = input
const panelCodes = new Set(input.panelFindings?.map((finding) => finding.code))
@@ -220,6 +244,7 @@ function exposureChecks(input: HealthDebugInput): HealthDebugCheck[] {
export function buildHealthDebugChecks(input: HealthDebugInput): HealthDebugCheck[] {
return [
...flagStateChecks(input),
+ ...splitChangedChecks(input),
...flagVariantsChecks(input),
...forcedVariantChecks(input),
...noMetricChecks(input),
diff --git a/products/experiments/frontend/health/healthPanelFindings.ts b/products/experiments/frontend/health/healthPanelFindings.ts
index 8dc86a7dff8a..5574d10015bf 100644
--- a/products/experiments/frontend/health/healthPanelFindings.ts
+++ b/products/experiments/frontend/health/healthPanelFindings.ts
@@ -6,7 +6,10 @@ import type { ExperimentHealthApi, ExperimentHealthFindingApi } from '../generat
import type { ExperimentHealthFindingActionKind, ExperimentHealthFindingCode } from './experimentHealthFindingEvents'
/** A finding of the health panel, from the experiment read or from the exposure answer. */
-export type HealthPanelFinding = Pick<ExperimentHealthFindingApi, 'subcode' | 'severity' | 'title' | 'detail'> & {
+export type HealthPanelFinding = Pick<
+ ExperimentHealthFindingApi,
+ 'subcode' | 'severity' | 'title' | 'detail' | 'evidence'
+> & {
code: ExperimentHealthFindingCode
actions: ExperimentHealthFindingActionKind[]
}
diff --git a/products/experiments/frontend/health/useHealthFindingReporting.ts b/products/experiments/frontend/health/useHealthFindingReporting.ts
index eb882192ec08..e5d2d328096a 100644
--- a/products/experiments/frontend/health/useHealthFindingReporting.ts
+++ b/products/experiments/frontend/health/useHealthFindingReporting.ts
@@ -28,29 +28,31 @@ export function useHealthFindingReporting(
useActions(experimentLogic)
const code = finding?.code
const variant = finding?.variant
+ const severity = finding?.severity
+ const reason = finding?.reason
useEffect(() => {
if (code && isShown) {
- reportHealthFindingShown({ code, variant })
+ reportHealthFindingShown({ code, variant, severity, reason })
}
- }, [code, variant, isShown, experimentLoadCount, reportHealthFindingShown])
+ }, [code, variant, severity, reason, isShown, experimentLoadCount, reportHealthFindingShown])
const reportOpened = useCallback(
(openKind: ExperimentHealthFindingOpenKind): void => {
if (code) {
- reportHealthFindingOpened({ code, variant }, openKind)
+ reportHealthFindingOpened({ code, variant, severity, reason }, openKind)
}
},
- [code, variant, reportHealthFindingOpened]
+ [code, variant, severity, reason, reportHealthFindingOpened]
)
const reportActedOn = useCallback(
(actionKind: ExperimentHealthFindingActionKind): void => {
if (code) {
- reportHealthFindingActedOn({ code, variant }, actionKind)
+ reportHealthFindingActedOn({ code, variant, severity, reason }, actionKind)
}
},
- [code, variant, reportHealthFindingActedOn]
+ [code, variant, severity, reason, reportHealthFindingActedOn]
)
return { reportOpened, reportActedOn }
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6ac97a570451..4813dd500c86 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -44588,6 +44588,7 @@ export namespace Schemas {
* * `zero_exposures` - Zero Exposures
* * `forced_variant_release_condition` - Forced Variant Release Condition
* * `flag_variants_mismatch` - Flag Variants Mismatch
+ * * `split_changed_mid_run` - Split Changed Mid Run
*/
export type ExperimentHealthFindingCodeEnum = typeof ExperimentHealthFindingCodeEnum[keyof typeof ExperimentHealthFindingCodeEnum];
@@ -44603,6 +44604,7 @@ export namespace Schemas {
ZeroExposures: 'zero_exposures',
ForcedVariantReleaseCondition: 'forced_variant_release_condition',
FlagVariantsMismatch: 'flag_variants_mismatch',
+ SplitChangedMidRun: 'split_changed_mid_run',
} as const;
/**
@@ -44621,6 +44623,7 @@ export namespace Schemas {
/**
* * `open_feature_flag` - Open Feature Flag
+ * * `open_feature_flag_history` - Open Feature Flag History
* * `adjust_distribution` - Adjust Distribution
* * `use_first_seen_variant` - Use First Seen Variant
* * `add_primary_metric` - Add Primary Metric
@@ -44633,6 +44636,7 @@ export namespace Schemas {
export const ExperimentHealthFindingActionKindEnum = {
OpenFeatureFlag: 'open_feature_flag',
+ OpenFeatureFlagHistory: 'open_feature_flag_history',
AdjustDistribution: 'adjust_distribution',
UseFirstSeenVariant: 'use_first_seen_variant',
AddPrimaryMetric: 'add_primary_metric',
@@ -44644,7 +44648,7 @@ export namespace Schemas {
/**
* The values behind the finding, such as the key of a shipped variant or the share of users exposed to multiple variants. The keys depend on the code.
*/
- export type ExperimentHealthFindingEvidence = {[key: string]: string | number | null};
+ export type ExperimentHealthFindingEvidence = {[key: string]: string | number | boolean | null};
export interface ExperimentHealthFinding {
/** Stable identifier of the problem. Each code has one meaning across every surface that reports it.
@@ -44658,7 +44662,8 @@ export namespace Schemas {
* * `srm` - Sample Ratio Mismatch
* * `zero_exposures` - Zero Exposures
* * `forced_variant_release_condition` - Forced Variant Release Condition
- * * `flag_variants_mismatch` - Flag Variants Mismatch */
+ * * `flag_variants_mismatch` - Flag Variants Mismatch
+ * * `split_changed_mid_run` - Split Changed Mid Run */
code: ExperimentHealthFindingCodeEnum;
/**
* The case within the code, when a code covers several, for example 'running_but_no_rollout' within 'flag_off_while_running'. Null when the code has one case.