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): grade pinned release conditions by their traffic (#117617)

Marcel Poelker15b036bda67d
diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.py
index b6085267ed68..91a6b234fa4e 100644
--- a/products/experiments/backend/facade/api.py
+++ b/products/experiments/backend/facade/api.py
@@ -5,6 +5,7 @@ This module provides the public interface for creating and managing experiments
using framework-free DTOs, wrapping the existing ExperimentService.
"""
+from dataclasses import replace
from uuid import UUID
from rest_framework.exceptions import ValidationError
@@ -13,6 +14,7 @@ from posthog.models.team import Team
from posthog.models.user import User
from products.experiments.backend.experiment_service import ExperimentService
+from products.experiments.backend.health.condition_set_traffic import load_condition_set_traffic
from products.experiments.backend.health.context import load_health_context
from products.experiments.backend.health.exposure_gate import load_split_history
from products.experiments.backend.health.registry import (
@@ -130,7 +132,7 @@ 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."""
+ changes of the flag's split since launch and the flag's recent calls, as far as `reader_access` allows."""
experiment = (
ExperimentModel.objects.filter(team_id=team_id)
.select_related("team", "feature_flag")
@@ -139,7 +141,8 @@ def get_experiment_health_findings(
)
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)
+ traffic = load_condition_set_traffic(experiment, context, reader_access=reader_access)
+ return evaluate_health(replace(context, condition_set_traffic=traffic), 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 6b1100ff205f..5003f8b89b44 100644
--- a/products/experiments/backend/facade/contracts.py
+++ b/products/experiments/backend/facade/contracts.py
@@ -151,6 +151,7 @@ class ExperimentHealthReaderAccess:
can_read_flag_history: bool
can_query_events: bool
+ denied_event_properties: frozenset[str]
@dataclass(frozen=True)
diff --git a/products/experiments/backend/health/checks/forced_variant.py b/products/experiments/backend/health/checks/forced_variant.py
index faeb3fb9c4f2..1fbbe7fd6a22 100644
--- a/products/experiments/backend/health/checks/forced_variant.py
+++ b/products/experiments/backend/health/checks/forced_variant.py
@@ -7,7 +7,11 @@ instead of the variant from the hash. An override that names no variant is ignor
See `get_match` in rust/feature-flags/src/flags/flag_matching.rs and `pinned_variant` in flag_operations.rs.
"""
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
+from datetime import datetime, timedelta
+from enum import StrEnum
+
+from posthog.dataclasses import frozen
from products.experiments.backend.facade.contracts import (
ExperimentHealthFinding,
@@ -16,7 +20,8 @@ from products.experiments.backend.facade.contracts import (
ExperimentHealthFindingSeverity,
)
from products.experiments.backend.health.checks.flag_state import is_single_variant_shipped, shipped_variant_key
-from products.experiments.backend.health.context import HealthContext
+from products.experiments.backend.health.context import ConditionSetTraffic, HealthContext, ReachableCondition, Split
+from products.experiments.backend.health.split_changes import format_change_time
# pinned: the subcodes are sent as `finding_variant` on the health finding events, so insights group on them.
# Every condition that includes users pins a variant, so no user is randomly assigned. One variant gets
@@ -26,36 +31,129 @@ ALL_CONDITIONS_PINNED = "all_conditions_pinned"
# assignment, so they bias the comparison unless the analysis excludes them, for example as test users.
SOME_CONDITIONS_PINNED = "some_conditions_pinned"
+# The severity of SOME_CONDITIONS_PINNED follows the largest share that pinned users make up of one variant's users,
+# in this window, or since launch or the flag's last save if later. The bias is per variant, so a few pinned users
+# weigh more in a small variant. Below the first share they can't move a variant's results much, so there is no
+# finding. Above the second they are a warning.
+TRAFFIC_WINDOW = timedelta(days=7)
+_NO_FINDING_BELOW_SHARE = 0.01
+_WARNING_ABOVE_SHARE = 0.05
+# With fewer people, the share of a few pinned people is mostly chance.
+_MIN_MATCHED_PEOPLE = 100
+# Only calls that the flag service evaluated name a condition set. When fewer calls than this share did, the
+# pinned users can be among the calls that name none, so a share under the first threshold does not clear the
+# finding. A share above it still counts, because the pinned users it found are real.
+_MIN_REMOTELY_EVALUATED_SHARE_TO_CLEAR = 0.5
+
+
+class PinnedShareUnknownReason(StrEnum):
+ # pinned: the finding's `evidence.reason`, which the health finding events track.
+ NOT_MEASURED = "not_measured"
+ TOO_FEW_PEOPLE = "too_few_people"
+ # Most calls carry no version: local evaluation in a server SDK, a bootstrap, or the customer's own assignment.
+ EVALUATED_OUTSIDE_FLAG_SERVICE = "evaluated_outside_flag_service"
+
+
+@frozen
+class _Pins:
+ pinned: tuple[ReachableCondition, ...]
+ all_pinned: bool
+ # The pinned conditions whose variant the analysis includes, in evaluation order.
+ analyzed: tuple[ReachableCondition, ...]
+ weighted: tuple[ReachableCondition, ...]
+ split: Split
+ # The analyzed pins to a variant with 0% in the split. The split sends nobody there, so they don't bias the
+ # other variants, but that variant's results show only the pinned users.
+ unweighted: tuple[ReachableCondition, ...]
+
+
+@frozen
+class _Measurement:
+ most_pinned_variant: str
+ pinned_people: int
+ # The variant's pinned people, and its weight in the split of the people assigned at random.
+ variant_people: float
+ # The people that a condition set served, without those pinned to a variant with 0% in the split.
+ matched_people: int
+ remotely_evaluated_share: float | None
+ since: datetime
+ team_timezone: str
+
+ @property
+ def share(self) -> float:
+ return self.pinned_people / self.variant_people if self.variant_people else 0.0
+
+
+@frozen
+class _Grade:
+ """The share that sets the severity of SOME_CONDITIONS_PINNED, or the reason it is unknown."""
+
+ measurement: _Measurement | None
+ share: float | None
+ unknown_reason: PinnedShareUnknownReason | None
+
+ def evidence(self) -> dict[str, str | int | float | None]:
+ evidence: dict[str, str | int | float | None] = {}
+ if self.measurement is not None:
+ remotely_evaluated_share = self.measurement.remotely_evaluated_share
+ evidence["most_pinned_variant"] = self.measurement.most_pinned_variant
+ evidence["pinned_people"] = self.measurement.pinned_people
+ evidence["variant_people"] = round(self.measurement.variant_people)
+ evidence["matched_people"] = self.measurement.matched_people
+ evidence["remotely_evaluated_share"] = (
+ None if remotely_evaluated_share is None else round(remotely_evaluated_share, 4)
+ )
+ if self.share is not None:
+ evidence["pinned_share"] = round(self.share, 4)
+ if self.unknown_reason is not None:
+ evidence["reason"] = self.unknown_reason.value
+ return evidence
+
+ def sentence(self, them: str) -> str:
+ """The measured share in words, or why it can't be measured, after a leading space. Empty otherwise."""
+ measurement = self.measurement
+ if self.share is not None and measurement is not None:
+ return (
+ f" Since {format_change_time(measurement.since, measurement.team_timezone)}, about "
+ f'{_percent(self.share)} of the users who got "{measurement.most_pinned_variant}" matched {them} '
+ f"({measurement.pinned_people:,} of about {round(measurement.variant_people):,})."
+ )
+ if self.unknown_reason == PinnedShareUnknownReason.EVALUATED_OUTSIDE_FLAG_SERVICE:
+ return (
+ " Most of this flag's calls are evaluated locally in a server SDK, bootstrapped, or assigned in your "
+ f"own code, so PostHog can't measure how many users match {them}."
+ )
+ return ""
+
+
+def needs_condition_set_traffic(ctx: HealthContext) -> bool:
+ """Whether the check grades SOME_CONDITIONS_PINNED by the users the pinned conditions served."""
+ pins = _pins(ctx)
+ return ctx.is_launched and pins is not None and not pins.all_pinned and bool(pins.weighted)
+
+
+def has_too_few_people(ctx: HealthContext, traffic: ConditionSetTraffic) -> bool:
+ """Whether the check leaves the share of `traffic` unknown only because too few people count."""
+ pins = _pins(ctx)
+ return (
+ pins is not None
+ and bool(pins.weighted)
+ and _grade(pins, traffic).unknown_reason == PinnedShareUnknownReason.TOO_FEW_PEOPLE
+ )
+
def forced_variant_release_condition(ctx: HealthContext) -> ExperimentHealthFinding | None:
flag = ctx.flag
- # After the end the flag often holds the shipped decision, not the setup of the run.
- if flag is None or flag.deleted or ctx.has_ended or ctx.archived:
- return None
-
- live_conditions = flag.reachable_conditions
- pinned = [
- (condition.number, condition.pinned_variant)
- for condition in live_conditions
- if condition.pinned_variant is not None
- ]
- if not pinned:
+ pins = _pins(ctx)
+ if flag is None or pins is None:
return None
- pinned_numbers = [number for number, _ in pinned]
- pinned_keys = list(dict.fromkeys(key for _, key in pinned))
is_draft = not ctx.is_launched
- if len(pinned) < len(live_conditions):
- return _finding(
- subcode=SOME_CONDITIONS_PINNED,
- severity=ExperimentHealthFindingSeverity.INFO,
- title="Some users are not randomly assigned to a variant",
- detail=_some_pinned_detail(pinned_numbers, pinned_keys, is_draft),
- pinned_numbers=pinned_numbers,
- pinned_keys=pinned_keys,
- diagnostic_ref="A7",
- )
+ if not pins.all_pinned:
+ return _some_conditions_pinned(pins, ctx.condition_set_traffic, is_draft)
+ pinned_numbers = [condition.number for condition in pins.pinned]
+ pinned_keys = _variant_keys(pins.pinned)
# The shipped finding already says that everyone gets this variant.
if ctx.is_running and is_single_variant_shipped(flag) and pinned_keys == [shipped_variant_key(flag)]:
return None
@@ -70,6 +168,108 @@ def forced_variant_release_condition(ctx: HealthContext) -> ExperimentHealthFind
)
+def _pins(ctx: HealthContext) -> _Pins | None:
+ flag = ctx.flag
+ # After the end the flag often holds the shipped decision, not the setup of the run.
+ if flag is None or flag.deleted or ctx.has_ended or ctx.archived:
+ return None
+ pinned = tuple(condition for condition in flag.reachable_conditions if condition.pinned_variant is not None)
+ if not pinned:
+ return None
+ # A variant that the experiment excludes is not in the results, so its pins can't bias them.
+ analyzed = tuple(condition for condition in pinned if condition.pinned_variant not in ctx.excluded_variant_keys)
+ unweighted_keys = {variant.key for variant in flag.variants if variant.rollout_percentage == 0}
+ return _Pins(
+ pinned=pinned,
+ all_pinned=len(pinned) == len(flag.reachable_conditions),
+ analyzed=analyzed,
+ weighted=tuple(condition for condition in analyzed if condition.pinned_variant not in unweighted_keys),
+ split=flag.variants,
+ unweighted=tuple(condition for condition in analyzed if condition.pinned_variant in unweighted_keys),
+ )
+
+
+def _some_conditions_pinned(
+ pins: _Pins, traffic: ConditionSetTraffic | None, is_draft: bool
+) -> ExperimentHealthFinding | None:
+ if not pins.analyzed:
+ return None
+ grade = None if is_draft or not pins.weighted else _grade(pins, traffic)
+ share = grade.share if grade is not None else None
+ if share is not None and share < _NO_FINDING_BELOW_SHARE and not pins.unweighted:
+ return None
+ pinned_numbers = [condition.number for condition in pins.analyzed]
+ pinned_keys = _variant_keys(pins.analyzed)
+ return _finding(
+ subcode=SOME_CONDITIONS_PINNED,
+ severity=ExperimentHealthFindingSeverity.WARNING
+ if share is not None and share > _WARNING_ABOVE_SHARE
+ else ExperimentHealthFindingSeverity.INFO,
+ title="Some users are not randomly assigned to a variant",
+ detail=_some_pinned_detail(pinned_numbers, pinned_keys, is_draft, grade, _variant_keys(pins.unweighted)),
+ pinned_numbers=pinned_numbers,
+ pinned_keys=pinned_keys,
+ diagnostic_ref="A7",
+ grade_evidence=grade.evidence() if grade is not None else {},
+ )
+
+
+def _grade(pins: _Pins, traffic: ConditionSetTraffic | None) -> _Grade:
+ if traffic is None:
+ return _Grade(measurement=None, share=None, unknown_reason=PinnedShareUnknownReason.NOT_MEASURED)
+ measurement = _measure(pins, traffic)
+ remotely_evaluated_share = measurement.remotely_evaluated_share
+ unknown_reason = (
+ PinnedShareUnknownReason.EVALUATED_OUTSIDE_FLAG_SERVICE
+ if remotely_evaluated_share is not None and remotely_evaluated_share < _MIN_REMOTELY_EVALUATED_SHARE_TO_CLEAR
+ else PinnedShareUnknownReason.TOO_FEW_PEOPLE
+ )
+ if measurement.matched_people < _MIN_MATCHED_PEOPLE:
+ return _Grade(measurement=measurement, share=None, unknown_reason=unknown_reason)
+ share = measurement.share
+ clearing_needs_more_calls = (
+ remotely_evaluated_share is None or remotely_evaluated_share < _MIN_REMOTELY_EVALUATED_SHARE_TO_CLEAR
+ )
+ if share < _NO_FINDING_BELOW_SHARE and clearing_needs_more_calls:
+ return _Grade(measurement=measurement, share=None, unknown_reason=unknown_reason)
+ return _Grade(measurement=measurement, share=share, unknown_reason=None)
+
+
+def _measure(pins: _Pins, traffic: ConditionSetTraffic) -> _Measurement:
+ excluded_numbers = {condition.number for condition in pins.unweighted}
+ matched_people = sum(people for number, people in traffic.people_by_set.items() if number not in excluded_numbers)
+ pinned_by_variant = dict.fromkeys(_variant_keys(pins.weighted), 0)
+ for condition in pins.weighted:
+ if condition.pinned_variant is not None:
+ pinned_by_variant[condition.pinned_variant] += traffic.people_by_set.get(condition.number, 0)
+ randomized_people = matched_people - sum(pinned_by_variant.values())
+ weights = {variant.key: variant.rollout_percentage for variant in pins.split}
+
+ def variant_people(key: str) -> float:
+ weight = weights.get(key)
+ # An unreadable weight counts as the whole split, which gives the lowest share the pins can have.
+ return pinned_by_variant[key] + randomized_people * (1.0 if weight is None else weight / 100)
+
+ def share(key: str) -> float:
+ people = variant_people(key)
+ return pinned_by_variant[key] / people if people else 0.0
+
+ most_pinned_variant = max(pinned_by_variant, key=share)
+ return _Measurement(
+ most_pinned_variant=most_pinned_variant,
+ pinned_people=pinned_by_variant[most_pinned_variant],
+ variant_people=variant_people(most_pinned_variant),
+ matched_people=matched_people,
+ remotely_evaluated_share=traffic.remotely_evaluated_calls / traffic.calls if traffic.calls else None,
+ since=traffic.since,
+ team_timezone=traffic.team_timezone,
+ )
+
+
+def _variant_keys(conditions: Sequence[ReachableCondition]) -> list[str]:
+ return list(dict.fromkeys(condition.pinned_variant for condition in conditions if condition.pinned_variant))
+
+
def _quoted(keys: Sequence[str]) -> str:
return ", ".join(f'"{key}"' for key in keys)
@@ -112,7 +312,13 @@ def _all_pinned_detail(numbers: Sequence[int], pinned_keys: Sequence[str], is_dr
return f"{fact} {why} {fix}"
-def _some_pinned_detail(numbers: Sequence[int], pinned_keys: Sequence[str], is_draft: bool) -> str:
+def _some_pinned_detail(
+ numbers: Sequence[int],
+ pinned_keys: Sequence[str],
+ is_draft: bool,
+ grade: _Grade | None,
+ unweighted_keys: Sequence[str],
+) -> str:
if len(numbers) == 1:
key = pinned_keys[0]
overrides, them = "the override", "it"
@@ -140,9 +346,23 @@ def _some_pinned_detail(numbers: Sequence[int], pinned_keys: Sequence[str], is_d
"If these are internal or test users, check that the filter for internal and test users excludes "
f"them from the results. Otherwise remove {overrides}."
)
+ if grade is not None:
+ fact += grade.sentence(them)
+ if len(unweighted_keys) == 1:
+ fact += (
+ f' Nobody gets "{unweighted_keys[0]}" at random, so the results of "{unweighted_keys[0]}" show only '
+ "these users."
+ )
+ elif unweighted_keys:
+ names = " or ".join(f'"{key}"' for key in unweighted_keys)
+ fact += f" Nobody gets {names} at random, so their results show only these users."
return f"{fact} {why} {fix}"
+def _percent(share: float) -> str:
+ return f"{share * 100:.1f}".removesuffix(".0") + "%"
+
+
def _finding(
*,
subcode: str,
@@ -152,6 +372,7 @@ def _finding(
pinned_numbers: Sequence[int],
pinned_keys: Sequence[str],
diagnostic_ref: str,
+ grade_evidence: Mapping[str, str | int | float | None] | None = None,
) -> ExperimentHealthFinding:
return ExperimentHealthFinding(
code=ExperimentHealthFindingCode.FORCED_VARIANT_RELEASE_CONDITION,
@@ -162,6 +383,7 @@ def _finding(
evidence={
"pinned_condition_sets": ", ".join(str(number) for number in pinned_numbers),
"pinned_variant_keys": ", ".join(pinned_keys),
+ **(grade_evidence or {}),
},
actions=(ExperimentHealthFindingActionKind.EDIT_RELEASE_CONDITIONS,),
diagnostic_ref=diagnostic_ref,
diff --git a/products/experiments/backend/health/condition_set_traffic.py b/products/experiments/backend/health/condition_set_traffic.py
new file mode 100644
index 000000000000..4d49778b089b
--- /dev/null
+++ b/products/experiments/backend/health/condition_set_traffic.py
@@ -0,0 +1,250 @@
+"""
+Loads the `$feature_flag_called` events of a running experiment's flag in the last days, by the release condition
+set that served each person. The forced-variant check grades its finding by the share of people that the pinned
+sets served. These are the people the flag served a variant, not the exposures that the experiment's exposure
+criteria count when they name another event, filters or an action, so the finding speaks of the users who got a
+variant.
+
+The flag service names the set in the reason "Matched condition set N", numbered from 1 in the stored order of the
+conditions (`get_reason_description` in rust/feature-flags/src/api/types.rs). Only calls of the flag's current
+version count, so the numbers match the conditions that the check reads. No call before the flag's last save can
+carry that version, so the scan starts there at the earliest.
+
+The scan runs without the reader, and every reader shares its cached answer. So it skips the filter for internal
+and test users: that filter often reads person properties or cohorts, which is too slow for a request, and it can
+read tables that a reader may not query.
+"""
+
+import json
+import hashlib
+from dataclasses import asdict
+from datetime import datetime, timedelta
+from time import monotonic, sleep
+from uuid import UUID
+
+from django.core.cache import cache
+from django.utils import timezone
+
+from posthog.schema import HogQLQueryModifiers, PersonsOnEventsMode
+
+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.exceptions_capture import capture_exception
+from posthog.utils import safe_cache_add
+
+from products.experiments.backend.facade.contracts import ExperimentHealthReaderAccess
+from products.experiments.backend.health.checks.forced_variant import (
+ TRAFFIC_WINDOW,
+ has_too_few_people,
+ needs_condition_set_traffic,
+)
+from products.experiments.backend.health.context import ConditionSetTraffic, HealthContext
+from products.experiments.backend.health.exposure_gate import UNKNOWN, cache_failed_scan
+from products.experiments.backend.hogql_queries.exposure_query_logic import (
+ DEFAULT_EXPOSURE_EVENT,
+ exposure_event_name_filter,
+ get_entity_key,
+ multivariate_flag_response_expr,
+)
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
+from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_mode
+
+QUERY_TIMEOUT_SECONDS = 10
+_ANSWER_CACHE_SECONDS = int(timedelta(days=1).total_seconds())
+# Too few people to grade usually means that the window started recently, at launch or at a save of the flag.
+# It fills up, so the answer is asked again sooner.
+_TOO_FEW_PEOPLE_CACHE_SECONDS = int(timedelta(hours=1).total_seconds())
+_MATCHED_REASON = "^Matched condition set ([0-9]+)$"
+# The scan runs without the reader, so it can't apply a reader's property access rules. A reader denied one of
+# these gets no share instead of counts derived from it.
+_SCANNED_PROPERTIES = frozenset(
+ {"$feature_flag", "$feature_flag_response", "$feature_flag_reason", "$feature_flag_version"}
+)
+_MAX_CONDITION_SETS = 1000
+_SCAN_LOCK_SECONDS = QUERY_TIMEOUT_SECONDS + 5
+_WAIT_FOR_SCAN_SECONDS = QUERY_TIMEOUT_SECONDS + 1
+_WAIT_STEP_SECONDS = 0.25
+
+
+def load_condition_set_traffic(
+ experiment: Experiment, ctx: HealthContext, *, reader_access: ExperimentHealthReaderAccess
+) -> ConditionSetTraffic | None:
+ """
+ The traffic of the experiment's flag when the forced-variant check grades by it, or None. None also when
+ unknown. Never raises: the health endpoint serves the other findings when this fails.
+ """
+ if (
+ not reader_access.can_query_events
+ or reader_access.denied_event_properties & _SCANNED_PROPERTIES
+ or not needs_condition_set_traffic(ctx)
+ ):
+ return None
+ try:
+ return _load_condition_set_traffic(experiment, ctx)
+ except Exception as error:
+ capture_exception(error)
+ return None
+
+
+def query_condition_set_traffic(
+ experiment: Experiment, *, window_start: datetime, window_end: datetime
+) -> ConditionSetTraffic:
+ """The calls of the experiment's flag in `[window_start, window_end)`."""
+ team = experiment.team
+ flag = experiment.feature_flag
+ query = parse_select(
+ """
+ SELECT condition_set, count(), sum(calls), sum(remotely_evaluated_calls)
+ FROM (
+ SELECT
+ {entity} AS entity,
+ argMaxIf(
+ toInt(extract(properties.$feature_flag_reason, {matched_reason})),
+ timestamp,
+ toFloat(properties.$feature_flag_version) = {flag_version}
+ AND match(properties.$feature_flag_reason, {matched_reason})
+ ) AS condition_set,
+ count() AS calls,
+ countIf(isNotNull(toFloat(properties.$feature_flag_version))) AS remotely_evaluated_calls
+ FROM events
+ WHERE {flag_calls}
+ AND timestamp >= {window_start} AND timestamp < {window_end}
+ AND properties.$feature_flag = {flag_key}
+ AND {returned_variant}
+ GROUP BY entity
+ )
+ GROUP BY condition_set
+ LIMIT {max_rows}
+ """,
+ placeholders={
+ "flag_calls": exposure_event_name_filter(
+ DEFAULT_EXPOSURE_EVENT, read_copies=_reads_exposure_copies(team.organization_id)
+ ),
+ "entity": ast.Field(chain=[get_entity_key(flag.aggregation_group_type_index)]),
+ "matched_reason": ast.Constant(value=_MATCHED_REASON),
+ "flag_version": ast.Constant(value=flag.version),
+ "window_start": ast.Constant(value=window_start),
+ "window_end": ast.Constant(value=window_end),
+ "flag_key": ast.Constant(value=flag.key),
+ # A call that returned no variant, such as "Out of rollout bound", put nobody in the experiment, so it
+ # must not count toward the share of calls that name a set.
+ "returned_variant": multivariate_flag_response_expr(),
+ # One row per condition set, plus one for people without a matched set. HogQL adds LIMIT 100 otherwise.
+ "max_rows": ast.Constant(value=_MAX_CONDITION_SETS + 1),
+ },
+ )
+ 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 gate, because every reader gets the cached answer.
+ response = execute_hogql_query(
+ query,
+ team=team,
+ # The join that applies person merges costs seconds on large teams and moves the counts by a tiny
+ # fraction, because a merge moves few people.
+ modifiers=HogQLQueryModifiers(
+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS
+ ),
+ # A profile that breaks on timeout returns partial counts, which would read as a smaller share.
+ settings=HogQLGlobalSettings(max_execution_time=QUERY_TIMEOUT_SECONDS, timeout_overflow_mode="throw"),
+ )
+ people_by_set: dict[int, int] = {}
+ calls = remotely_evaluated_calls = 0
+ for condition_set, people, set_calls, set_remotely_evaluated_calls in response.results or []:
+ if condition_set:
+ people_by_set[int(condition_set)] = int(people)
+ calls += int(set_calls)
+ remotely_evaluated_calls += int(set_remotely_evaluated_calls)
+ return ConditionSetTraffic(
+ since=window_start,
+ team_timezone=team.timezone,
+ people_by_set=people_by_set,
+ calls=calls,
+ remotely_evaluated_calls=remotely_evaluated_calls,
+ )
+
+
+def _reads_exposure_copies(organization_id: UUID) -> bool:
+ # On FLAG_EVALUATIONS_ONLY, events hold no `$feature_flag_called` for the teams in ingestion's allowlist. The
+ # `$experiment_exposure` copy carries every property, the reason and the version included. A team can still
+ # write both, and then each person counts once under their latest set.
+ return get_organization_flag_evaluations_mode(organization_id) == FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY
+
+
+def _load_condition_set_traffic(experiment: Experiment, ctx: HealthContext) -> ConditionSetTraffic | None:
+ launched_at = experiment.start_date
+ if launched_at is None or experiment.feature_flag.version is None:
+ return None
+ cache_key = _cache_key(experiment, launched_at)
+ hit, traffic = _cached(cache_key)
+ if hit:
+ return traffic
+ # Readers share one scan. A request that finds another scan in flight waits for its answer. The lock is
+ # never released: every scan caches an answer, which readers check first, so the lock only has to expire.
+ if not safe_cache_add(f"{cache_key}:scanning", True, _SCAN_LOCK_SECONDS):
+ return _wait_for_scan(cache_key)
+ # A scan can finish between the read above and the lock.
+ hit, traffic = _cached(cache_key)
+ if hit:
+ return traffic
+ return _scan(experiment, ctx, cache_key, launched_at)
+
+
+def _scan(
+ experiment: Experiment, ctx: HealthContext, cache_key: str, launched_at: datetime
+) -> ConditionSetTraffic | None:
+ flag = experiment.feature_flag
+ now = timezone.now()
+ window_start = max(launched_at, flag.updated_at or launched_at, now - TRAFFIC_WINDOW)
+ try:
+ traffic = query_condition_set_traffic(experiment, window_start=window_start, window_end=now)
+ except Exception as error:
+ cache_failed_scan(cache_key, error)
+ return None
+ cache.set(
+ cache_key,
+ asdict(traffic),
+ _TOO_FEW_PEOPLE_CACHE_SECONDS if has_too_few_people(ctx, traffic) else _ANSWER_CACHE_SECONDS,
+ )
+ return traffic
+
+
+def _cached(cache_key: str) -> tuple[bool, ConditionSetTraffic | None]:
+ """Whether the cache holds an answer, and the answer. A failed scan is cached as UNKNOWN, and answers None."""
+ cached = cache.get(cache_key)
+ if isinstance(cached, dict):
+ return True, ConditionSetTraffic(**cached)
+ return cached == UNKNOWN, None
+
+
+def _wait_for_scan(cache_key: str) -> ConditionSetTraffic | None:
+ """The answer of the scan in flight, or None when it does not arrive within the query timeout."""
+ deadline = monotonic() + _WAIT_FOR_SCAN_SECONDS
+ while monotonic() < deadline:
+ sleep(_WAIT_STEP_SECONDS)
+ hit, traffic = _cached(cache_key)
+ if hit:
+ return traffic
+ return None
+
+
+def _cache_key(experiment: Experiment, launched_at: datetime) -> str:
+ flag = experiment.feature_flag
+ # Every input of the query except the end of the window, which moves with the clock.
+ inputs = json.dumps(
+ [
+ launched_at.isoformat(),
+ flag.key,
+ flag.version,
+ flag.updated_at.isoformat() if flag.updated_at else None,
+ flag.aggregation_group_type_index,
+ ],
+ sort_keys=True,
+ )
+ digest = hashlib.sha256(inputs.encode()).hexdigest()
+ return f"experiment_condition_set_traffic:{experiment.team_id}:{experiment.id}:{digest}"
diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.py
index 86bf36426699..df3fdef0be77 100644
--- a/products/experiments/backend/health/context.py
+++ b/products/experiments/backend/health/context.py
@@ -86,6 +86,20 @@ class FlagState:
reachable_conditions: tuple[ReachableCondition, ...]
+@frozen
+class ConditionSetTraffic:
+ """The flag's `$feature_flag_called` events of the last days, by the release condition that served each person."""
+
+ # The latest of launch, the flag's last save and the start of the window.
+ since: datetime
+ team_timezone: str
+ # People by the condition set that served their latest call of the flag's current version.
+ people_by_set: Mapping[int, int]
+ # The calls that returned a variant, and those of them that the flag service evaluated, which alone name a set.
+ calls: int
+ remotely_evaluated_calls: int
+
+
@frozen
class ExposureTotals:
total_exposures: Mapping[str, int]
@@ -112,6 +126,10 @@ class HealthContext:
exposures: ExposureTotals | None
# None when not loaded. Only the health endpoint loads it, because it can query the exposures.
split_history: SplitHistory | SplitHistoryNotChecked | None
+ # None when not loaded or unknown. Only the health endpoint loads it, because it queries the events.
+ condition_set_traffic: ConditionSetTraffic | None
+ # The variants that the analysis leaves out of the results.
+ excluded_variant_keys: frozenset[str]
def parse_flag_state(
@@ -212,4 +230,6 @@ def load_health_context(
secondary_metric_count=len(experiment.metrics_secondary or []) + shared_metric_roles.count("secondary"),
exposures=exposures,
split_history=split_history,
+ condition_set_traffic=None,
+ excluded_variant_keys=frozenset(experiment.excluded_variants or []),
)
diff --git a/products/experiments/backend/health/exposure_gate.py b/products/experiments/backend/health/exposure_gate.py
index 23e3658bfdec..997eb567d032 100644
--- a/products/experiments/backend/health/exposure_gate.py
+++ b/products/experiments/backend/health/exposure_gate.py
@@ -71,7 +71,7 @@ _ANSWER_CACHE_SECONDS = int(timedelta(days=30).total_seconds())
# 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"
+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.
@@ -100,6 +100,17 @@ def load_split_history(
return None
+def cache_failed_scan(cache_key: str, error: Exception) -> None:
+ """Caches the answer of a failed scan as UNKNOWN, and reports an error that is not expected."""
+ # 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)
+
+
def query_any_exposure(
experiment: Experiment,
*,
@@ -180,7 +191,7 @@ class _ExposureGate:
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:
+ if cached == UNKNOWN:
return None
if self._stopped:
return None
@@ -198,13 +209,7 @@ class _ExposureGate:
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)
+ cache_failed_scan(cache_key, error)
self._stopped = True
return None
settled = answer or timezone.now() - window.end > _SETTLED_AFTER
diff --git a/products/experiments/backend/health/test/test_condition_set_traffic.py b/products/experiments/backend/health/test/test_condition_set_traffic.py
new file mode 100644
index 000000000000..249173b1da2f
--- /dev/null
+++ b/products/experiments/backend/health/test/test_condition_set_traffic.py
@@ -0,0 +1,382 @@
+import time
+import threading
+from dataclasses import replace
+from datetime import UTC, 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 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.team.team import Team
+from posthog.models.user import User
+from posthog.test.persons import create_person
+
+from products.experiments.backend.facade.contracts import ExperimentHealthReaderAccess
+from products.experiments.backend.health.condition_set_traffic import (
+ load_condition_set_traffic,
+ query_condition_set_traffic,
+)
+from products.experiments.backend.health.context import ConditionSetTraffic, load_health_context
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfig
+
+FLAG_KEY = "pinned-share"
+FLAG_VERSION = 3
+FULL_ACCESS = ExperimentHealthReaderAccess(
+ can_read_flag_history=True, can_query_events=True, denied_event_properties=frozenset()
+)
+TRAFFIC = ConditionSetTraffic(
+ since=datetime(2026, 10, 1, tzinfo=UTC),
+ team_timezone="UTC",
+ people_by_set={1: 30, 2: 970},
+ calls=2000,
+ remotely_evaluated_calls=2000,
+)
+TOO_FEW_PEOPLE = ConditionSetTraffic(
+ since=datetime(2026, 10, 1, tzinfo=UTC),
+ team_timezone="UTC",
+ people_by_set={1: 3, 2: 50},
+ calls=100,
+ remotely_evaluated_calls=100,
+)
+_NO_VARIANT_REASONS = frozenset({"Out of rollout bound", "No matching condition set"})
+_STAFF_PINNED_TO_TEST: dict[str, Any] = {
+ "properties": [{"key": "email", "value": "@example.com", "operator": "icontains", "type": "person"}],
+ "rollout_percentage": 100,
+ "variant": "test",
+}
+# Set 1 pins a 0% holdout, so its 500 people do not count toward the minimum.
+TOO_FEW_PEOPLE_BESIDE_A_HOLDOUT = replace(TOO_FEW_PEOPLE, people_by_set={1: 500, 2: 3, 3: 50})
+_HOLDOUT_FILTERS: dict[str, Any] = {
+ "groups": [
+ {**_STAFF_PINNED_TO_TEST, "variant": "holdout"},
+ {
+ "properties": [{"key": "$device_type", "value": "iOS", "operator": "exact", "type": "person"}],
+ "rollout_percentage": 100,
+ "variant": "test",
+ },
+ {"properties": [], "rollout_percentage": 100},
+ ],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ {"key": "holdout", "rollout_percentage": 0},
+ ]
+ },
+}
+
+
+def _create_running_experiment(team: Team, user: User, *, launched_at: datetime) -> Experiment:
+ flag = FeatureFlag.objects.create(
+ team=team,
+ created_by=user,
+ key=FLAG_KEY,
+ version=FLAG_VERSION,
+ filters={
+ "groups": [_STAFF_PINNED_TO_TEST, {"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [{"key": "control", "rollout_percentage": 50}, {"key": "test", "rollout_percentage": 50}]
+ },
+ },
+ )
+ return Experiment.objects.create(team=team, name="Pinned share", feature_flag=flag, start_date=launched_at)
+
+
+class TestLoadConditionSetTraffic(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ self.experiment = _create_running_experiment(
+ self.team, self.user, launched_at=timezone.now() - timedelta(days=30)
+ )
+
+ def _load(
+ self, answer: ConditionSetTraffic | Exception, *, reader_access: ExperimentHealthReaderAccess = FULL_ACCESS
+ ) -> tuple[ConditionSetTraffic | None, MagicMock]:
+ with patch(
+ "products.experiments.backend.health.condition_set_traffic.query_condition_set_traffic",
+ side_effect=[answer],
+ ) as query:
+ traffic = load_condition_set_traffic(
+ self.experiment, load_health_context(self.experiment), reader_access=reader_access
+ )
+ return traffic, query
+
+ @parameterized.expand(
+ [
+ ("no_query_access", replace(FULL_ACCESS, can_query_events=False)),
+ ("denied_the_reason", replace(FULL_ACCESS, denied_event_properties=frozenset({"$feature_flag_reason"}))),
+ ]
+ )
+ def test_reader_who_cannot_read_the_flag_calls_gets_no_traffic(
+ self, _name: str, reader_access: ExperimentHealthReaderAccess
+ ) -> None:
+ traffic, query = self._load(TRAFFIC, reader_access=reader_access)
+
+ self.assertEqual((traffic, query.call_count), (None, 0))
+
+ @parameterized.expand(
+ [
+ ("since_launch", timedelta(days=2), timedelta(days=3), "launch"),
+ ("since_the_last_save", timedelta(days=30), timedelta(hours=2), "save"),
+ ("last_seven_days", timedelta(days=30), timedelta(days=20), "window"),
+ ]
+ )
+ def test_window_starts_at_the_latest_of_launch_last_save_and_seven_days_ago(
+ self, _name: str, launched_ago: timedelta, saved_ago: timedelta, expected_start: str
+ ) -> None:
+ now = timezone.now()
+ Experiment.objects.filter(pk=self.experiment.pk).update(start_date=now - launched_ago)
+ FeatureFlag.objects.filter(pk=self.experiment.feature_flag_id).update(updated_at=now - saved_ago)
+ self.experiment = Experiment.objects.get(pk=self.experiment.pk)
+
+ with time_machine.travel(now, tick=False):
+ _, query = self._load(TRAFFIC)
+
+ starts = {"launch": now - launched_ago, "save": now - saved_ago, "window": now - timedelta(days=7)}
+ self.assertEqual(query.call_args.kwargs["window_start"], starts[expected_start])
+
+ @parameterized.expand(
+ [
+ ("enough_people_hours_later", TRAFFIC, timedelta(hours=12), 0),
+ ("enough_people_a_day_later", TRAFFIC, timedelta(days=1, minutes=1), 1),
+ ("too_few_people_minutes_later", TOO_FEW_PEOPLE, timedelta(minutes=30), 0),
+ ("too_few_people_an_hour_later", TOO_FEW_PEOPLE, timedelta(hours=1, minutes=1), 1),
+ (
+ "too_few_people_beside_a_holdout_an_hour_later",
+ TOO_FEW_PEOPLE_BESIDE_A_HOLDOUT,
+ timedelta(hours=1, minutes=1),
+ 1,
+ _HOLDOUT_FILTERS,
+ ),
+ ]
+ )
+ def test_answer_cache(
+ self,
+ _name: str,
+ answer: ConditionSetTraffic,
+ next_load_after: timedelta,
+ expected_queries: int,
+ flag_filters: dict[str, Any] | None = None,
+ ) -> None:
+ if flag_filters is not None:
+ FeatureFlag.objects.filter(pk=self.experiment.feature_flag_id).update(filters=flag_filters)
+ self.experiment = Experiment.objects.get(pk=self.experiment.pk)
+ first, _ = self._load(answer)
+
+ with time_machine.travel(timezone.now() + next_load_after):
+ next_load, query = self._load(answer)
+
+ self.assertEqual((first, next_load, query.call_count), (answer, answer, expected_queries))
+
+ @parameterized.expand(
+ [
+ ("scan_succeeds", TRAFFIC, TRAFFIC),
+ ("scan_fails", RuntimeError("unexpected"), None),
+ ]
+ )
+ def test_concurrent_load_waits_for_the_scan_in_flight(
+ self, _name: str, scan_answer: ConditionSetTraffic | Exception, expected: ConditionSetTraffic | None
+ ) -> None:
+ ctx = load_health_context(self.experiment)
+ scanning = threading.Event()
+ second_load_waits = threading.Event()
+ first_load: list[ConditionSetTraffic | None] = []
+
+ def scan(*_args: Any, **_kwargs: Any) -> ConditionSetTraffic:
+ scanning.set()
+ second_load_waits.wait(timeout=5)
+ if isinstance(scan_answer, Exception):
+ raise scan_answer
+ return scan_answer
+
+ def wait_a_moment(_seconds: float) -> None:
+ second_load_waits.set()
+ time.sleep(0.01)
+
+ with (
+ patch(
+ "products.experiments.backend.health.condition_set_traffic.query_condition_set_traffic",
+ side_effect=scan,
+ ) as query,
+ patch("products.experiments.backend.health.condition_set_traffic.sleep", side_effect=wait_a_moment),
+ patch("products.experiments.backend.health.exposure_gate.capture_exception"),
+ ):
+ first = threading.Thread(
+ target=lambda: first_load.append(
+ load_condition_set_traffic(self.experiment, ctx, reader_access=FULL_ACCESS)
+ )
+ )
+ first.start()
+ scanning.wait(timeout=5)
+ second_load = load_condition_set_traffic(self.experiment, ctx, reader_access=FULL_ACCESS)
+ first.join(timeout=5)
+
+ self.assertEqual((first_load, second_load, query.call_count), ([expected], expected, 1))
+
+ def test_concurrent_load_stops_waiting_after_the_query_timeout(self) -> None:
+ ctx = load_health_context(self.experiment)
+ scanning = threading.Event()
+ release_scan = threading.Event()
+
+ def scan(*_args: Any, **_kwargs: Any) -> ConditionSetTraffic:
+ scanning.set()
+ release_scan.wait(timeout=5)
+ return TRAFFIC
+
+ with (
+ patch(
+ "products.experiments.backend.health.condition_set_traffic.query_condition_set_traffic",
+ side_effect=scan,
+ ) as query,
+ patch("products.experiments.backend.health.condition_set_traffic._WAIT_FOR_SCAN_SECONDS", 0.05),
+ ):
+ first = threading.Thread(
+ target=lambda: load_condition_set_traffic(self.experiment, ctx, reader_access=FULL_ACCESS)
+ )
+ first.start()
+ scanning.wait(timeout=5)
+ second_load = load_condition_set_traffic(self.experiment, ctx, reader_access=FULL_ACCESS)
+ release_scan.set()
+ first.join(timeout=5)
+
+ self.assertEqual((second_load, query.call_count), (None, 1))
+
+ @parameterized.expand(
+ [
+ ("scan_too_expensive", ClickHouseQueryTimeOut(), False, 0),
+ ("transient_memory_pressure", ClickHouseClusterMemoryLimitExceeded(), False, 1),
+ ("unexpected_error", RuntimeError("unexpected"), True, 1),
+ ]
+ )
+ def test_failed_query_is_unknown_and_not_retried_on_the_next_load(
+ self, _name: str, error: Exception, reported: bool, queries_two_hours_later: int
+ ) -> None:
+ with patch("products.experiments.backend.health.exposure_gate.capture_exception") as capture:
+ traffic, _ = self._load(error)
+ next_load, next_query = self._load(TRAFFIC)
+ with time_machine.travel(timezone.now() + timedelta(hours=2)):
+ _, later_query = self._load(TRAFFIC)
+
+ self.assertEqual(
+ (traffic, next_load, next_query.call_count, capture.called, later_query.call_count),
+ (None, None, 0, reported, queries_two_hours_later),
+ )
+
+
+class TestQueryConditionSetTraffic(ClickhouseTestMixin, BaseTest):
+ @parameterized.expand(
+ [
+ (
+ "calls_of_another_flag_version_name_no_set",
+ [
+ ("person-1", "Matched condition set 1", FLAG_VERSION, 1),
+ ("person-2", "Matched condition set 1", 2, 1),
+ ],
+ ({1: 1}, 2, 2),
+ ),
+ (
+ "calls_evaluated_outside_the_flag_service_name_no_set",
+ [
+ ("person-1", "Matched condition set 2", FLAG_VERSION, 1),
+ ("person-2", None, None, 1),
+ ("person-3", "Evaluated locally", None, 1),
+ ],
+ ({2: 1}, 3, 1),
+ ),
+ (
+ "calls_that_return_no_variant_do_not_count",
+ [
+ ("person-1", "Out of rollout bound", FLAG_VERSION, 1),
+ ("person-2", "Matched condition set 2", FLAG_VERSION, 1),
+ ],
+ ({2: 1}, 1, 1),
+ ),
+ (
+ "person_counts_once_under_the_latest_set",
+ [
+ ("person-1", "Matched condition set 1", FLAG_VERSION, 2),
+ ("person-1", "Matched condition set 2", FLAG_VERSION, 1),
+ ],
+ ({2: 1}, 2, 2),
+ ),
+ (
+ "calls_outside_the_window",
+ [
+ ("person-1", "Matched condition set 1", FLAG_VERSION, 1),
+ ("person-2", "Matched condition set 1", FLAG_VERSION, 8),
+ ],
+ ({1: 1}, 1, 1),
+ ),
+ ]
+ )
+ def test_query_condition_set_traffic(
+ self,
+ _name: str,
+ calls: list[tuple[str, str | None, int | None, int]],
+ expected: tuple[dict[int, int], int, int],
+ ) -> None:
+ now = timezone.now()
+ experiment = _create_running_experiment(self.team, self.user, launched_at=now - timedelta(days=30))
+ for distinct_id in dict.fromkeys(distinct_id for distinct_id, *_ in calls):
+ create_person(team=self.team, distinct_ids=[distinct_id])
+ for distinct_id, reason, version, days_ago in calls:
+ self._call_flag(distinct_id, reason, version, now - timedelta(days=days_ago))
+ flush_persons_and_events()
+
+ traffic = query_condition_set_traffic(experiment, window_start=now - timedelta(days=7), window_end=now)
+
+ self.assertEqual((dict(traffic.people_by_set), traffic.calls, traffic.remotely_evaluated_calls), expected)
+
+ @parameterized.expand(
+ [
+ ("events", FlagEvaluationsMode.EVENTS, ({}, 0, 0)),
+ ("flag_evaluations_only", FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY, ({1: 1}, 1, 1)),
+ ]
+ )
+ def test_reads_the_exposure_copy_only_where_flag_calls_leave_events(
+ self, _name: str, mode: FlagEvaluationsMode, expected: tuple[dict[int, int], int, int]
+ ) -> None:
+ OrganizationFeatureFlagsConfig.objects.update_or_create(
+ organization=self.organization, defaults={"flag_evaluations_mode": mode}
+ )
+ now = timezone.now()
+ experiment = _create_running_experiment(self.team, self.user, launched_at=now - timedelta(days=30))
+ create_person(team=self.team, distinct_ids=["person-1"])
+ self._call_flag(
+ "person-1", "Matched condition set 1", FLAG_VERSION, now - timedelta(days=1), event="$experiment_exposure"
+ )
+ flush_persons_and_events()
+
+ traffic = query_condition_set_traffic(experiment, window_start=now - timedelta(days=7), window_end=now)
+
+ self.assertEqual((dict(traffic.people_by_set), traffic.calls, traffic.remotely_evaluated_calls), expected)
+
+ def _call_flag(
+ self,
+ distinct_id: str,
+ reason: str | None,
+ version: int | None,
+ at: datetime,
+ *,
+ event: str = "$feature_flag_called",
+ ) -> None:
+ properties: dict[str, Any] = {
+ "$feature_flag": FLAG_KEY,
+ "$feature_flag_response": False if reason in _NO_VARIANT_REASONS else "test",
+ }
+ if reason is not None:
+ properties["$feature_flag_reason"] = reason
+ if version is not None:
+ properties["$feature_flag_version"] = version
+ _create_event(team=self.team, event=event, distinct_id=distinct_id, properties=properties, timestamp=at)
diff --git a/products/experiments/backend/health/test/test_exposure_gate.py b/products/experiments/backend/health/test/test_exposure_gate.py
index f294d1549ca6..da51af703c3a 100644
--- a/products/experiments/backend/health/test/test_exposure_gate.py
+++ b/products/experiments/backend/health/test/test_exposure_gate.py
@@ -32,7 +32,9 @@ 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)
+FULL_ACCESS = ExperimentHealthReaderAccess(
+ can_read_flag_history=True, can_query_events=True, denied_event_properties=frozenset()
+)
_BY_EVENT_PROPERTY: dict[str, Any] = {
"exposure_config": {
"kind": "ExperimentEventExposureConfig",
@@ -194,7 +196,9 @@ class TestLoadSplitHistory(BaseTest):
history, query = self._load(
[True],
reader_access=ExperimentHealthReaderAccess(
- can_read_flag_history=can_read_flag_history, can_query_events=can_query_events
+ can_read_flag_history=can_read_flag_history,
+ can_query_events=can_query_events,
+ denied_event_properties=frozenset(),
),
)
@@ -207,7 +211,13 @@ class TestLoadSplitHistory(BaseTest):
@parameterized.expand(
[
("exposure_filters", _BY_EVENT_PROPERTY, FULL_ACCESS),
- ("no_query_access", {}, ExperimentHealthReaderAccess(can_read_flag_history=True, can_query_events=False)),
+ (
+ "no_query_access",
+ {},
+ ExperimentHealthReaderAccess(
+ can_read_flag_history=True, can_query_events=False, denied_event_properties=frozenset()
+ ),
+ ),
]
)
def test_flag_without_split_changes_needs_no_check(
diff --git a/products/experiments/backend/health/test/test_flag_state.py b/products/experiments/backend/health/test/test_flag_state.py
index ae4b869e2adc..453bf7b121bd 100644
--- a/products/experiments/backend/health/test/test_flag_state.py
+++ b/products/experiments/backend/health/test/test_flag_state.py
@@ -63,6 +63,8 @@ def _context(
secondary_metric_count=0,
exposures=None,
split_history=None,
+ condition_set_traffic=None,
+ excluded_variant_keys=frozenset(),
)
diff --git a/products/experiments/backend/health/test/test_flag_variants.py b/products/experiments/backend/health/test/test_flag_variants.py
index b9f42c5245a3..2bd3c4857551 100644
--- a/products/experiments/backend/health/test/test_flag_variants.py
+++ b/products/experiments/backend/health/test/test_flag_variants.py
@@ -39,6 +39,8 @@ def _context(
secondary_metric_count=0,
exposures=None,
split_history=None,
+ condition_set_traffic=None,
+ excluded_variant_keys=frozenset(),
)
diff --git a/products/experiments/backend/health/test/test_forced_variant.py b/products/experiments/backend/health/test/test_forced_variant.py
index b655befac3ea..9448e4c16383 100644
--- a/products/experiments/backend/health/test/test_forced_variant.py
+++ b/products/experiments/backend/health/test/test_forced_variant.py
@@ -1,3 +1,4 @@
+from datetime import UTC, datetime
from typing import Any
from unittest import TestCase
@@ -5,11 +6,15 @@ from unittest import TestCase
from parameterized import parameterized
from products.experiments.backend.facade.contracts import ExperimentHealthFindingSeverity
-from products.experiments.backend.health.checks.forced_variant import forced_variant_release_condition
-from products.experiments.backend.health.context import HealthContext, parse_flag_state
+from products.experiments.backend.health.checks.forced_variant import (
+ forced_variant_release_condition,
+ needs_condition_set_traffic,
+)
+from products.experiments.backend.health.context import ConditionSetTraffic, HealthContext, parse_flag_state
EVEN_SPLIT = [{"key": "control", "rollout_percentage": 50}, {"key": "test", "rollout_percentage": 50}]
SHIPPED_SPLIT = [{"key": "control", "rollout_percentage": 0}, {"key": "test", "rollout_percentage": 100}]
+SPLIT_WITH_HOLDOUT = [*EVEN_SPLIT, {"key": "holdout", "rollout_percentage": 0}]
EVERYONE: dict[str, Any] = {"properties": [], "rollout_percentage": 100}
STAFF: dict[str, Any] = {
"properties": [{"key": "email", "value": "@example.com", "operator": "icontains", "type": "person"}],
@@ -32,6 +37,8 @@ def _context(
variants: list[dict[str, Any]] = EVEN_SPLIT,
deleted: bool = False,
early_exit: bool = False,
+ traffic: ConditionSetTraffic | None = None,
+ excluded: frozenset[str] = frozenset(),
) -> HealthContext:
return HealthContext(
**status,
@@ -43,6 +50,19 @@ def _context(
secondary_metric_count=0,
exposures=None,
split_history=None,
+ condition_set_traffic=traffic,
+ excluded_variant_keys=excluded,
+ )
+
+
+def _traffic(people_by_set: dict[int, int], *, remotely_evaluated: float = 1.0) -> ConditionSetTraffic:
+ calls = 2 * sum(people_by_set.values())
+ return ConditionSetTraffic(
+ since=datetime(2026, 10, 12, 13, 4, tzinfo=UTC),
+ team_timezone="Europe/Berlin",
+ people_by_set=people_by_set,
+ calls=calls,
+ remotely_evaluated_calls=round(calls * remotely_evaluated),
)
@@ -53,22 +73,22 @@ class TestForcedVariantReleaseCondition(TestCase):
(
"qa_override_before_randomized_set",
_context([{**STAFF, "variant": "test"}, EVERYONE]),
- ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "1", "test"),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "1", "test", None),
),
(
"draft_qa_override",
_context([{**STAFF, "variant": "test"}, EVERYONE], status=DRAFT),
- ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "1", "test"),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "1", "test", None),
),
(
"catch_all_override",
_context([{**EVERYONE, "variant": "control"}]),
- ("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "control"),
+ ("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "control", None),
),
(
"cohorts_forced_into_both_variants",
_context([{**IOS, "variant": "test"}, {**STAFF, "variant": "control"}]),
- ("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1, 2", "test, control"),
+ ("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1, 2", "test, control", None),
),
("override_after_a_catch_all_is_unreachable", _context([EVERYONE, {**STAFF, "variant": "test"}]), None),
(
@@ -81,7 +101,7 @@ class TestForcedVariantReleaseCondition(TestCase):
_context(
[{**STAFF, "variant": "test", "rollout_percentage": 0}, {**IOS, "variant": "control"}, EVERYONE]
),
- ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "2", "control"),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "2", "control", None),
),
("override_naming_no_variant_is_ignored", _context([{**STAFF, "variant": "old-test"}, EVERYONE]), None),
(
@@ -92,17 +112,107 @@ class TestForcedVariantReleaseCondition(TestCase):
(
"override_contradicts_the_shipped_variant",
_context([{**EVERYONE, "variant": "control"}], variants=SHIPPED_SPLIT),
- ("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "control"),
+ ("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "control", None),
),
("ended", _context([{**EVERYONE, "variant": "control"}], status=ENDED), None),
("deleted_flag", _context([{**EVERYONE, "variant": "control"}], deleted=True), None),
+ (
+ "pinned_share_under_one_percent",
+ _context([{**STAFF, "variant": "test"}, EVERYONE], traffic=_traffic({1: 5, 2: 995})),
+ None,
+ ),
+ (
+ "pinned_share_of_a_few_percent",
+ _context([{**STAFF, "variant": "test"}, EVERYONE], traffic=_traffic({1: 15, 2: 985})),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "1", "test", 0.0296),
+ ),
+ (
+ "pinned_share_of_five_percent",
+ _context([{**STAFF, "variant": "test"}, EVERYONE], traffic=_traffic({1: 50, 2: 1900})),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "1", "test", 0.05),
+ ),
+ (
+ "pinned_share_above_five_percent",
+ _context([{**STAFF, "variant": "test"}, EVERYONE], traffic=_traffic({1: 120, 2: 880})),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "test", 0.2143),
+ ),
+ (
+ "pins_to_two_variants_grade_by_the_most_affected",
+ _context(
+ [{**STAFF, "variant": "control"}, {**IOS, "variant": "test"}, EVERYONE],
+ traffic=_traffic({1: 10, 2: 30, 3: 960}),
+ ),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1, 2", "control, test", 0.0588),
+ ),
+ (
+ "pins_to_a_small_variant",
+ _context(
+ [{**STAFF, "variant": "test"}, EVERYONE],
+ variants=[{"key": "control", "rollout_percentage": 90}, {"key": "test", "rollout_percentage": 10}],
+ traffic=_traffic({1: 20, 2: 980}),
+ ),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "test", 0.1695),
+ ),
+ (
+ "too_few_people_to_measure",
+ _context([{**STAFF, "variant": "test"}, EVERYONE], traffic=_traffic({1: 60, 2: 39})),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "1", "test", None),
+ ),
+ (
+ "small_share_from_too_few_remotely_evaluated_calls",
+ _context(
+ [{**STAFF, "variant": "test"}, EVERYONE],
+ traffic=_traffic({1: 1, 2: 999}, remotely_evaluated=0.4),
+ ),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "1", "test", None),
+ ),
+ (
+ "large_share_from_too_few_remotely_evaluated_calls",
+ _context(
+ [{**STAFF, "variant": "test"}, EVERYONE],
+ traffic=_traffic({1: 120, 2: 880}, remotely_evaluated=0.4),
+ ),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "test", 0.2143),
+ ),
+ (
+ "pins_to_a_zero_percent_variant_the_analysis_shows",
+ _context([{**STAFF, "variant": "holdout"}, EVERYONE], variants=SPLIT_WITH_HOLDOUT),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "1", "holdout", None),
+ ),
+ (
+ "pins_to_a_zero_percent_variant_the_analysis_excludes",
+ _context(
+ [{**STAFF, "variant": "holdout"}, EVERYONE],
+ variants=SPLIT_WITH_HOLDOUT,
+ excluded=frozenset({"holdout"}),
+ ),
+ None,
+ ),
+ (
+ "pins_to_a_variant_the_analysis_excludes",
+ _context(
+ [{**STAFF, "variant": "test-2"}, EVERYONE],
+ variants=[*EVEN_SPLIT, {"key": "test-2", "rollout_percentage": 0}],
+ excluded=frozenset({"test-2"}),
+ ),
+ None,
+ ),
+ (
+ "pins_to_a_zero_percent_variant_stay_out_of_the_share",
+ _context(
+ [{**STAFF, "variant": "holdout"}, {**IOS, "variant": "test"}, EVERYONE],
+ variants=SPLIT_WITH_HOLDOUT,
+ traffic=_traffic({1: 500, 2: 30, 3: 470}),
+ ),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1, 2", "holdout, test", 0.1132),
+ ),
]
)
def test_forced_variant_release_condition(
self,
_name: str,
ctx: HealthContext,
- expected: tuple[str, ExperimentHealthFindingSeverity, str, str] | None,
+ expected: tuple[str, ExperimentHealthFindingSeverity, str, str, float | None] | None,
) -> None:
finding = forced_variant_release_condition(ctx)
@@ -116,7 +226,62 @@ class TestForcedVariantReleaseCondition(TestCase):
finding.severity,
finding.evidence["pinned_condition_sets"],
finding.evidence["pinned_variant_keys"],
+ finding.evidence.get("pinned_share"),
),
expected,
)
self.assertEqual("before launch" in finding.detail, not ctx.is_launched)
+ self.assertEqual("of the users who got" in finding.detail, expected[4] is not None)
+ self.assertEqual('Nobody gets "holdout" at random' in finding.detail, "holdout" in expected[3])
+
+ @parameterized.expand(
+ [
+ ("not_measured", _context([{**STAFF, "variant": "test"}, EVERYONE]), "not_measured", False),
+ (
+ "too_few_people",
+ _context([{**STAFF, "variant": "test"}, EVERYONE], traffic=_traffic({1: 60, 2: 39})),
+ "too_few_people",
+ False,
+ ),
+ (
+ "evaluated_outside_flag_service",
+ _context(
+ [{**STAFF, "variant": "test"}, EVERYONE],
+ traffic=_traffic({1: 1, 2: 999}, remotely_evaluated=0.4),
+ ),
+ "evaluated_outside_flag_service",
+ True,
+ ),
+ (
+ "measured",
+ _context([{**STAFF, "variant": "test"}, EVERYONE], traffic=_traffic({1: 30, 2: 970})),
+ None,
+ False,
+ ),
+ ("draft", _context([{**STAFF, "variant": "test"}, EVERYONE], status=DRAFT), None, False),
+ ]
+ )
+ def test_an_unknown_share_names_its_reason(
+ self, _name: str, ctx: HealthContext, expected_reason: str | None, says_not_measurable: bool
+ ) -> None:
+ finding = forced_variant_release_condition(ctx)
+
+ assert finding is not None
+ self.assertEqual(
+ (finding.evidence.get("reason"), "can't measure" in finding.detail), (expected_reason, says_not_measurable)
+ )
+
+ @parameterized.expand(
+ [
+ ("some_conditions_pinned", _context([{**STAFF, "variant": "test"}, EVERYONE]), True),
+ ("draft", _context([{**STAFF, "variant": "test"}, EVERYONE], status=DRAFT), False),
+ ("all_conditions_pinned", _context([{**STAFF, "variant": "test"}, {**IOS, "variant": "control"}]), False),
+ (
+ "pins_to_a_zero_percent_variant_only",
+ _context([{**STAFF, "variant": "holdout"}, EVERYONE], variants=SPLIT_WITH_HOLDOUT),
+ False,
+ ),
+ ]
+ )
+ def test_needs_condition_set_traffic(self, _name: str, ctx: HealthContext, expected: bool) -> None:
+ self.assertIs(needs_condition_set_traffic(ctx), expected)
diff --git a/products/experiments/backend/health/test/test_no_metric.py b/products/experiments/backend/health/test/test_no_metric.py
index 9675317facf3..91e7b7849955 100644
--- a/products/experiments/backend/health/test/test_no_metric.py
+++ b/products/experiments/backend/health/test/test_no_metric.py
@@ -22,6 +22,8 @@ def _context(**changes: Any) -> HealthContext:
"secondary_metric_count": 0,
"exposures": None,
"split_history": None,
+ "condition_set_traffic": None,
+ "excluded_variant_keys": frozenset(),
}
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 c8352a0273eb..6368a640e320 100644
--- a/products/experiments/backend/health/test/test_registry.py
+++ b/products/experiments/backend/health/test/test_registry.py
@@ -42,6 +42,8 @@ RUNNING_UNEVEN_SPLIT = HealthContext(
secondary_metric_count=0,
exposures=UNEVEN_SPLIT_TOTALS,
split_history=None,
+ condition_set_traffic=None,
+ excluded_variant_keys=frozenset(),
)
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
index 66e3dd0ff2ea..763115fcb691 100644
--- a/products/experiments/backend/health/test/test_split_changed.py
+++ b/products/experiments/backend/health/test/test_split_changed.py
@@ -87,6 +87,8 @@ def _context(
else SplitHistoryNotChecked(
reason=not_checked, launched_at=launched_at, team_timezone="Europe/Berlin", changes=changes
),
+ condition_set_traffic=None,
+ excluded_variant_keys=frozenset(),
)
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index e854150991e6..16f4e48b7c9f 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -67,6 +67,10 @@ from posthog.temporal.common.client import sync_connect
from posthog.temporal.experiments.models import ExperimentTimeseriesRecalculationWorkflowInputs
from posthog.user_permissions import UserPermissions
+from products.access_control.backend.facade.api import (
+ get_restricted_properties_with_group_type_index_for_team,
+ split_restricted_property_names,
+)
from products.access_control.backend.facade.user_access_control import (
UserAccessControl,
access_level_satisfied_for_resource,
@@ -917,6 +921,19 @@ class EnterpriseExperimentsViewSet(
`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.
+
+ The severity of the `some_conditions_pinned` finding follows the largest share that the
+ users of the pinned release conditions make up among the users who got one variant from
+ the flag, in the last 7 days, or since launch or the flag's last save if later. It reads
+ the flag's calls that name the matched condition, not the experiment's exposure criteria:
+ info up to 5%, warning above, and no finding under 1% when at least half of the calls
+ that returned a variant name a condition. The finding is info when the share is unknown,
+ and `evidence.reason` says why: `not_measured` (for example an API key without
+ `query:read`, or a caller denied a flag call property), `too_few_people` (under 100), or
+ `evaluated_outside_flag_service` (most calls come from local evaluation, a bootstrap or
+ the caller's own assignment). A pin to a variant with 0% in the split adds an info,
+ because that variant's results show only the pinned users, unless the experiment
+ excludes the variant from the analysis.
"""
experiment: Experiment = self.get_object()
findings = get_experiment_health_findings(
@@ -938,9 +955,13 @@ class EnterpriseExperimentsViewSet(
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"
)
+ restrictions = get_restricted_properties_with_group_type_index_for_team(
+ user=cast(User, request.user), team_id=self.team_id
+ )
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,
+ denied_event_properties=split_restricted_property_names(restrictions).event,
)
@validated_request(
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index c8cb51f5fa24..af618051b8b0 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -3933,7 +3933,7 @@ class TestExperimentService(APIBaseTest):
0,
["forced_variant_release_condition"],
["forced_variant_release_condition:some_conditions_pinned"],
- ["forced_variant_release_condition:some_conditions_pinned:info:"],
+ ["forced_variant_release_condition:some_conditions_pinned:info:not_measured"],
)
],
),
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index ef8547bffc58..0464f1e8201c 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -29,7 +29,7 @@ from posthog.schema import (
from posthog.auth import IDJagAccessTokenAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.constants import AvailableFeature
-from posthog.models import Organization, OrganizationMembership, Team
+from posthog.models import Organization, OrganizationMembership, PropertyDefinition, Team
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.extensions import get_or_create_team_extension
@@ -37,11 +37,14 @@ from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.test.test_journeys import journeys_for
+from products.access_control.backend.facade.api import upsert_property_access_control
+from products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInput
from products.access_control.backend.models.access_control import AccessControl
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.experiments.backend.experiment_service import ExperimentService
+from products.experiments.backend.health.context import ConditionSetTraffic
from products.experiments.backend.hogql_queries.exposure_query_logic import (
EXPERIMENT_EXPOSURE_EVENT_CUTOFF,
EXPERIMENT_EXPOSURE_EVENT_FLAG,
@@ -78,6 +81,13 @@ def _make(cls, **attrs):
_HEALTH_PAUSED = ("flag_off_while_running", "running_but_flag_disabled")
+_HEALTH_TRAFFIC = ConditionSetTraffic(
+ since=datetime(2026, 10, 12, tzinfo=UTC),
+ team_timezone="UTC",
+ people_by_set={1: 120, 2: 880},
+ calls=2000,
+ remotely_evaluated_calls=2000,
+)
_HEALTH_METRIC = {
"kind": "ExperimentMetric",
"metric_type": "mean",
@@ -868,6 +878,96 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
]
self.assertEqual(split_findings, [expected_split_finding])
+ @parameterized.expand(
+ [
+ ("pinned_share_above_five_percent", None, _HEALTH_TRAFFIC, "warning"),
+ ("traffic_query_fails", None, RuntimeError("unexpected"), "info"),
+ ("token_without_query_scope", ["experiment:read", "activity_log:read"], _HEALTH_TRAFFIC, "info"),
+ ("reader_denied_the_reason", None, _HEALTH_TRAFFIC, "info", "$feature_flag_reason"),
+ ]
+ )
+ def test_health_grades_pinned_conditions_by_their_traffic(
+ self,
+ _name: str,
+ token_scopes: list[str] | None,
+ traffic: ConditionSetTraffic | Exception,
+ expected_severity: str,
+ denied_property: str | None = None,
+ ) -> None:
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key=f"health-pinned-{_name}",
+ created_by=self.user,
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": "email", "value": "@example.com", "operator": "icontains", "type": "person"}
+ ],
+ "rollout_percentage": 100,
+ "variant": "test",
+ },
+ {"properties": [], "rollout_percentage": 100},
+ ],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ experiment = Experiment.objects.create(
+ team=self.team,
+ name="health-pinned",
+ feature_flag=flag,
+ start_date=timezone.now() - timedelta(days=3),
+ metrics=[_HEALTH_METRIC],
+ )
+ if denied_property is not None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.PROPERTY_ACCESS_CONTROL, "name": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ denied = PropertyDefinition.objects.create(
+ team=self.team, name=denied_property, property_type="String", type=PropertyDefinition.Type.EVENT
+ )
+ upsert_property_access_control(
+ team_id=self.team.id,
+ created_by_id=self.user.id,
+ input=UpsertPropertyAccessControlInput(
+ property_definition_id=str(denied.id),
+ access_level=PropertyAccessLevel.NONE,
+ organization_member_id=self.organization_membership.id,
+ ),
+ )
+ headers: dict[str, str] = {}
+ if token_scopes is not None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ user=self.user, label="health", secure_value=hash_key_value(token), scopes=token_scopes
+ )
+ self.client.logout()
+ headers = {"authorization": f"Bearer {token}"}
+
+ with patch(
+ "products.experiments.backend.health.condition_set_traffic.query_condition_set_traffic",
+ side_effect=[traffic],
+ ):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/experiments/{experiment.id}/health/", headers=headers
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ self.assertEqual(
+ [
+ (finding["subcode"], finding["severity"])
+ for finding in response.json()["findings"]
+ if finding["code"] == "forced_variant_release_condition"
+ ],
+ [("some_conditions_pinned", expected_severity)],
+ )
+
def _rebalance_split_at(self, flag: FeatureFlag, at: datetime) -> None:
with time_machine.travel(at), self.captureOnCommitCallbacks(execute=True):
flag.filters = {
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index aab5ec89c699..9a71247b01d4 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -709,6 +709,19 @@ export const getExperimentsHealthRetrieveUrl = (projectId: string, id: number) =
* `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.
+ *
+ * The severity of the `some_conditions_pinned` finding follows the largest share that the
+ * users of the pinned release conditions make up among the users who got one variant from
+ * the flag, in the last 7 days, or since launch or the flag's last save if later. It reads
+ * the flag's calls that name the matched condition, not the experiment's exposure criteria:
+ * info up to 5%, warning above, and no finding under 1% when at least half of the calls
+ * that returned a variant name a condition. The finding is info when the share is unknown,
+ * and `evidence.reason` says why: `not_measured` (for example an API key without
+ * `query:read`, or a caller denied a flag call property), `too_few_people` (under 100), or
+ * `evaluated_outside_flag_service` (most calls come from local evaluation, a bootstrap or
+ * the caller's own assignment). A pin to a variant with 0% in the split adds an info,
+ * because that variant's results show only the pinned users, unless the experiment
+ * excludes the variant from the analysis.
*/
export const experimentsHealthRetrieve = async (
projectId: string,