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.

refactor(experiments): one home for the health checks' flag rules (#114739)

Marcel Poelker928b2a17b3cd
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index 25164c64258e..a5e2d0ba10f3 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -736,6 +736,7 @@
'get_status_display',
'get_type_display',
'holdout_id',
+ 'hours_since_launch',
'id',
'is_draft',
'is_exposure_frozen',
diff --git a/products/experiments/backend/health/checks/flag_state.py b/products/experiments/backend/health/checks/flag_state.py
index 20dd9b1b9f53..230fe7effc73 100644
--- a/products/experiments/backend/health/checks/flag_state.py
+++ b/products/experiments/backend/health/checks/flag_state.py
@@ -35,7 +35,7 @@ def flag_state(ctx: HealthContext) -> ExperimentHealthFinding | None:
single_variant_shipped = is_single_variant_shipped(flag)
if ctx.is_running:
- if not flag.active:
+ if ctx.is_paused:
return _finding(
code=ExperimentHealthFindingCode.FLAG_OFF_WHILE_RUNNING,
subcode=RUNNING_BUT_FLAG_DISABLED,
diff --git a/products/experiments/backend/health/checks/forced_variant.py b/products/experiments/backend/health/checks/forced_variant.py
index 338430b9b081..faeb3fb9c4f2 100644
--- a/products/experiments/backend/health/checks/forced_variant.py
+++ b/products/experiments/backend/health/checks/forced_variant.py
@@ -16,7 +16,7 @@ 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 FlagReleaseGroup, FlagState, HealthContext
+from products.experiments.backend.health.context import HealthContext
# 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
@@ -33,21 +33,25 @@ def forced_variant_release_condition(ctx: HealthContext) -> ExperimentHealthFind
if flag is None or flag.deleted or ctx.has_ended or ctx.archived:
return None
- variant_keys = {variant.key for variant in flag.variants if variant.key}
- live_sets = _live_condition_sets(flag)
- pinned_sets = [(number, group) for number, group in live_sets if group.variant in variant_keys]
- if not pinned_sets:
+ 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:
return None
- pinned_keys = list(dict.fromkeys(group.variant for _, group in pinned_sets if group.variant))
+ 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_sets) < len(live_sets):
+ 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([number for number, _ in pinned_sets], pinned_keys, is_draft),
- pinned_sets=pinned_sets,
+ detail=_some_pinned_detail(pinned_numbers, pinned_keys, is_draft),
+ pinned_numbers=pinned_numbers,
pinned_keys=pinned_keys,
diagnostic_ref="A7",
)
@@ -59,36 +63,13 @@ def forced_variant_release_condition(ctx: HealthContext) -> ExperimentHealthFind
subcode=ALL_CONDITIONS_PINNED,
severity=ExperimentHealthFindingSeverity.WARNING,
title="No users are randomly assigned to a variant",
- detail=_all_pinned_detail([number for number, _ in pinned_sets], pinned_keys, is_draft),
- pinned_sets=pinned_sets,
+ detail=_all_pinned_detail(pinned_numbers, pinned_keys, is_draft),
+ pinned_numbers=pinned_numbers,
pinned_keys=pinned_keys,
diagnostic_ref="A7b",
)
-def _live_condition_sets(flag: FlagState) -> list[tuple[int, FlagReleaseGroup]]:
- """The release conditions that can include users, numbered from 1 as the page labels them ("Set 2")."""
- # A request without a group's key skips that group's conditions, so a group condition ends the evaluation
- # only for the requests of its group type. A person condition ends it for every request.
- ended_group_types: set[int] = set()
- live: list[tuple[int, FlagReleaseGroup]] = []
- for number, group in enumerate(flag.release_groups, start=1):
- group_type = group.aggregation_group_type_index
- if group_type in ended_group_types:
- continue
- # A missing rollout serves every matched user, as on the flag service.
- rollout = 100 if group.rollout_percentage is None else group.rollout_percentage
- if rollout > 0:
- live.append((number, group))
- # A condition without properties matches every request that reaches it. At a full rollout, or with early
- # exit at any rollout including 0%, the evaluation ends there for all of them.
- if not group.property_count and (rollout >= 100 or flag.early_exit):
- if group_type is None:
- break
- ended_group_types.add(group_type)
- return live
-
-
def _quoted(keys: Sequence[str]) -> str:
return ", ".join(f'"{key}"' for key in keys)
@@ -168,7 +149,7 @@ def _finding(
severity: ExperimentHealthFindingSeverity,
title: str,
detail: str,
- pinned_sets: Sequence[tuple[int, FlagReleaseGroup]],
+ pinned_numbers: Sequence[int],
pinned_keys: Sequence[str],
diagnostic_ref: str,
) -> ExperimentHealthFinding:
@@ -179,7 +160,7 @@ def _finding(
title=title,
detail=detail,
evidence={
- "pinned_condition_sets": ", ".join(str(number) for number, _ in pinned_sets),
+ "pinned_condition_sets": ", ".join(str(number) for number in pinned_numbers),
"pinned_variant_keys": ", ".join(pinned_keys),
},
actions=(ExperimentHealthFindingActionKind.EDIT_RELEASE_CONDITIONS,),
diff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.py
index 9fd82a46d00f..00c5dc5df223 100644
--- a/products/experiments/backend/health/context.py
+++ b/products/experiments/backend/health/context.py
@@ -6,6 +6,7 @@ from posthog.dataclasses import frozen
from products.experiments.backend.metric_resolution import saved_metric_link_role, saved_metric_links
from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.facade.filters import pinned_variant, reachable_conditions
@frozen
@@ -18,12 +19,13 @@ class FlagVariant:
class FlagReleaseGroup:
rollout_percentage: float | None
property_count: int | None
- # The variant override of the release condition, as stored. The flag service ignores a key that is
- # not one of the flag's variants.
- variant: str | None
- # The group type the condition aggregates on, or None for persons. A condition without its own value
- # takes the flag's value, as `effective_aggregation` in rust/feature-flags/src/flags/flag_property_group.rs.
- aggregation_group_type_index: int | None
+
+
+@frozen
+class ReachableCondition:
+ # Numbered from 1, as the page labels the release conditions ("Set 2").
+ number: int
+ pinned_variant: str | None
@frozen
@@ -32,9 +34,8 @@ class FlagState:
deleted: bool
release_groups: tuple[FlagReleaseGroup, ...]
variants: tuple[FlagVariant, ...]
- # With early exit, the flag service stops at the first condition whose properties match, also when the
- # user falls outside that condition's rollout.
- early_exit: bool
+ # The release conditions that can serve a request, in evaluation order.
+ reachable_conditions: tuple[ReachableCondition, ...]
@frozen
@@ -51,17 +52,15 @@ class HealthContext:
"""Every input of the health checks, loaded once, so that each check is a pure function of it."""
is_launched: bool
+ is_running: bool
has_ended: bool
+ is_paused: bool
archived: bool
flag: FlagState | None
primary_metric_count: int
secondary_metric_count: int
exposures: ExposureTotals | None
- @property
- def is_running(self) -> bool:
- return self.is_launched and not self.has_ended
-
def parse_flag_state(
*,
@@ -69,44 +68,35 @@ def parse_flag_state(
deleted: bool,
groups: object,
variants: object,
- aggregation_group_type_index: object = None,
- early_exit: object = False,
+ aggregation_group_type_index: int | None = None,
+ early_exit: bool = False,
) -> FlagState:
- flag_aggregation = _group_type_index(aggregation_group_type_index)
+ conditions = groups if isinstance(groups, list) else []
+ flag_variants = tuple(_variant(variant) for variant in variants) if isinstance(variants, list) else ()
+ 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(
active=active,
deleted=deleted,
- release_groups=(
- tuple(_release_group(group, flag_aggregation) for group in groups) if isinstance(groups, list) else ()
+ release_groups=tuple(_release_group(group) for group in conditions),
+ variants=flag_variants,
+ reachable_conditions=tuple(
+ ReachableCondition(number=index + 1, pinned_variant=pinned_variant(conditions[index], variant_keys))
+ for index in reachable
),
- variants=tuple(_variant(variant) for variant in variants) if isinstance(variants, list) else (),
- early_exit=early_exit is True,
)
-def _release_group(group: object, flag_aggregation: int | None) -> FlagReleaseGroup:
+def _release_group(group: object) -> FlagReleaseGroup:
if not isinstance(group, dict):
- return FlagReleaseGroup(
- rollout_percentage=None, property_count=None, variant=None, aggregation_group_type_index=flag_aggregation
- )
+ return FlagReleaseGroup(rollout_percentage=None, property_count=None)
properties = group.get("properties")
- variant = group.get("variant")
return FlagReleaseGroup(
rollout_percentage=_percentage(group.get("rollout_percentage")),
property_count=len(properties) if isinstance(properties, list) else None,
- variant=variant if isinstance(variant, str) and variant else None,
- aggregation_group_type_index=(
- _group_type_index(group["aggregation_group_type_index"])
- if "aggregation_group_type_index" in group
- else flag_aggregation
- ),
)
-def _group_type_index(value: object) -> int | None:
- return value if isinstance(value, int) and not isinstance(value, bool) else None
-
-
def _variant(variant: object) -> FlagVariant:
if not isinstance(variant, dict):
return FlagVariant(key=None, rollout_percentage=None)
@@ -145,7 +135,9 @@ def load_health_context(experiment: Experiment, exposures: ExposureTotals | None
shared_metric_roles = [saved_metric_link_role(link) for link in saved_metric_links(experiment)]
return HealthContext(
is_launched=experiment.is_launched,
+ is_running=experiment.is_running,
has_ended=experiment.is_stopped,
+ is_paused=experiment.is_paused,
archived=experiment.archived,
flag=_load_flag_state(experiment),
primary_metric_count=len(experiment.metrics or []) + shared_metric_roles.count("primary"),
diff --git a/products/experiments/backend/health/test/test_flag_state.py b/products/experiments/backend/health/test/test_flag_state.py
index 267961793262..539ca790f50e 100644
--- a/products/experiments/backend/health/test/test_flag_state.py
+++ b/products/experiments/backend/health/test/test_flag_state.py
@@ -39,9 +39,9 @@ SHIPPED_TO_SOME = {
"multivariate": SHIPPED_VARIANT["multivariate"],
}
-RUNNING = {"is_launched": True, "has_ended": False}
-ENDED = {"is_launched": True, "has_ended": True}
-DRAFT = {"is_launched": False, "has_ended": False}
+RUNNING = {"is_launched": True, "is_running": True, "has_ended": False}
+ENDED = {"is_launched": True, "is_running": False, "has_ended": True}
+DRAFT = {"is_launched": False, "is_running": False, "has_ended": False}
def _context(
@@ -49,6 +49,7 @@ def _context(
) -> HealthContext:
return HealthContext(
**status,
+ is_paused=status["is_running"] and not active,
archived=archived,
flag=parse_flag_state(
active=active,
diff --git a/products/experiments/backend/health/test/test_forced_variant.py b/products/experiments/backend/health/test/test_forced_variant.py
index c1d021ad38e1..e1ee053cd3c8 100644
--- a/products/experiments/backend/health/test/test_forced_variant.py
+++ b/products/experiments/backend/health/test/test_forced_variant.py
@@ -20,9 +20,9 @@ IOS: dict[str, Any] = {
"rollout_percentage": 100,
}
-RUNNING = {"is_launched": True, "has_ended": False}
-ENDED = {"is_launched": True, "has_ended": True}
-DRAFT = {"is_launched": False, "has_ended": False}
+RUNNING = {"is_launched": True, "is_running": True, "has_ended": False}
+ENDED = {"is_launched": True, "is_running": False, "has_ended": True}
+DRAFT = {"is_launched": False, "is_running": False, "has_ended": False}
def _context(
@@ -35,6 +35,7 @@ def _context(
) -> HealthContext:
return HealthContext(
**status,
+ is_paused=False,
archived=False,
flag=parse_flag_state(active=True, deleted=deleted, groups=groups, variants=variants, early_exit=early_exit),
primary_metric_count=1,
@@ -62,57 +63,23 @@ class TestForcedVariantReleaseCondition(TestCase):
_context([{**EVERYONE, "variant": "control"}]),
("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "control"),
),
- (
- "catch_all_override_without_rollout",
- _context([{"properties": [], "variant": "test"}]),
- ("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "test"),
- ),
(
"cohorts_forced_into_both_variants",
_context([{**IOS, "variant": "test"}, {**STAFF, "variant": "control"}]),
("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1, 2", "test, control"),
),
- (
- "randomized_set_at_zero_rollout_randomizes_nobody",
- _context([{**IOS, "variant": "test"}, {**EVERYONE, "rollout_percentage": 0}]),
- ("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1", "test"),
- ),
- (
- "override_at_zero_rollout",
- _context([{**STAFF, "variant": "test", "rollout_percentage": 0}, EVERYONE]),
- None,
- ),
("override_after_a_catch_all_is_unreachable", _context([EVERYONE, {**STAFF, "variant": "test"}]), None),
- (
- "override_after_a_group_catch_all_in_a_mixed_flag",
- _context([{**EVERYONE, "aggregation_group_type_index": 0}, {**STAFF, "variant": "test"}]),
- ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "2", "test"),
- ),
- (
- "override_after_a_catch_all_of_the_same_group_type",
- _context(
- [
- {**EVERYONE, "aggregation_group_type_index": 0, "variant": "test"},
- {**EVERYONE, "aggregation_group_type_index": 0},
- {**STAFF, "variant": "control"},
- ]
- ),
- ("all_conditions_pinned", ExperimentHealthFindingSeverity.WARNING, "1, 3", "test, control"),
- ),
- (
- "override_after_a_zero_catch_all_with_early_exit",
- _context([{**EVERYONE, "rollout_percentage": 0}, {**EVERYONE, "variant": "control"}], early_exit=True),
- None,
- ),
(
"override_after_a_partial_catch_all_with_early_exit",
_context([{**EVERYONE, "rollout_percentage": 50}, {**STAFF, "variant": "test"}], early_exit=True),
None,
),
(
- "override_after_a_partial_catch_all",
- _context([{**EVERYONE, "rollout_percentage": 50}, {**STAFF, "variant": "test"}]),
- ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "2", "test"),
+ "set_numbers_follow_the_flag_order",
+ _context(
+ [{**STAFF, "variant": "test", "rollout_percentage": 0}, {**IOS, "variant": "control"}, EVERYONE]
+ ),
+ ("some_conditions_pinned", ExperimentHealthFindingSeverity.INFO, "2", "control"),
),
("override_naming_no_variant_is_ignored", _context([{**STAFF, "variant": "old-test"}, EVERYONE]), None),
(
diff --git a/products/experiments/backend/health/test/test_no_metric.py b/products/experiments/backend/health/test/test_no_metric.py
index e58913946362..9019f272d58f 100644
--- a/products/experiments/backend/health/test/test_no_metric.py
+++ b/products/experiments/backend/health/test/test_no_metric.py
@@ -12,7 +12,9 @@ from products.experiments.backend.health.context import HealthContext
def _context(**changes: Any) -> HealthContext:
values: dict[str, Any] = {
"is_launched": True,
+ "is_running": True,
"has_ended": False,
+ "is_paused": False,
"archived": False,
"flag": None,
"primary_metric_count": 0,
@@ -26,8 +28,8 @@ class TestNoMetric(TestCase):
@parameterized.expand(
[
("running_without_metrics", _context(), True),
- ("ended_without_metrics", _context(has_ended=True), True),
- ("draft_without_metrics", _context(is_launched=False), False),
+ ("ended_without_metrics", _context(is_running=False, has_ended=True), True),
+ ("draft_without_metrics", _context(is_launched=False, is_running=False), False),
("secondary_metric_only", _context(secondary_metric_count=1), False),
("primary_metric_only", _context(primary_metric_count=1), False),
]
diff --git a/products/experiments/backend/health/test/test_registry.py b/products/experiments/backend/health/test/test_registry.py
index c245a7167072..4d27b728ac0e 100644
--- a/products/experiments/backend/health/test/test_registry.py
+++ b/products/experiments/backend/health/test/test_registry.py
@@ -23,7 +23,9 @@ UNEVEN_SPLIT_TOTALS = ExposureTotals(
RUNNING_UNEVEN_SPLIT = HealthContext(
is_launched=True,
+ is_running=True,
has_ended=False,
+ is_paused=False,
archived=False,
flag=FlagState(
active=True,
@@ -33,7 +35,7 @@ RUNNING_UNEVEN_SPLIT = HealthContext(
FlagVariant(key="control", rollout_percentage=80),
FlagVariant(key="test", rollout_percentage=20),
),
- early_exit=False,
+ reachable_conditions=(),
),
primary_metric_count=1,
secondary_metric_count=0,
@@ -41,6 +43,7 @@ RUNNING_UNEVEN_SPLIT = HealthContext(
)
NO_EXPOSURES = replace(UNEVEN_SPLIT_TOTALS, total_exposures={"control": 0, "test": 0})
+ENDED: dict[str, Any] = {"is_running": False, "has_ended": True}
def _raise(_ctx: HealthContext) -> Any:
@@ -52,15 +55,15 @@ class TestEvaluate(TestCase):
[
("bias_risk_on_an_uneven_split", {}, [ExperimentHealthFindingCode.BIAS_RISK_MULTIPLE_EXCLUDED]),
("nothing_without_exposure_totals", {"exposures": None}, []),
- ("no_bias_risk_after_the_end", {"has_ended": True}, []),
+ ("no_bias_risk_after_the_end", ENDED, []),
(
"srm_below_the_threshold",
- {"has_ended": True, "exposures": replace(UNEVEN_SPLIT_TOTALS, sample_ratio_mismatch_p_value=0.0009)},
+ {**ENDED, "exposures": replace(UNEVEN_SPLIT_TOTALS, sample_ratio_mismatch_p_value=0.0009)},
[ExperimentHealthFindingCode.SRM],
),
(
"no_srm_at_the_threshold",
- {"has_ended": True, "exposures": replace(UNEVEN_SPLIT_TOTALS, sample_ratio_mismatch_p_value=0.001)},
+ {**ENDED, "exposures": replace(UNEVEN_SPLIT_TOTALS, sample_ratio_mismatch_p_value=0.001)},
[],
),
(
@@ -69,11 +72,15 @@ class TestEvaluate(TestCase):
[ExperimentHealthFindingCode.ZERO_EXPOSURES],
),
("no_zero_exposures_in_the_first_day", {"exposures": replace(NO_EXPOSURES, hours_since_launch=23.9)}, []),
- ("no_zero_exposures_before_launch", {"is_launched": False, "exposures": NO_EXPOSURES}, []),
+ (
+ "no_zero_exposures_before_launch",
+ {"is_launched": False, "is_running": False, "exposures": NO_EXPOSURES},
+ [],
+ ),
(
"no_zero_exposures_with_only_multiple_variant_users",
{
- "has_ended": True,
+ **ENDED,
"exposures": replace(NO_EXPOSURES, total_exposures={"control": 0, "test": 0, "$multiple": 3}),
},
[],
diff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
index 1ef5f988beb4..8111f34257da 100644
--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
@@ -282,10 +282,6 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
total_exposures=total_exposures,
)
- def _hours_since_launch(self) -> float | None:
- start_date = self.experiment.start_date
- return (datetime.now(UTC) - start_date).total_seconds() / 3600 if start_date else None
-
def _evaluate_health(self, exposures: ExposureTotals) -> list[ExperimentExposureHealthFinding]:
findings = evaluate_health(load_health_context(self.experiment, exposures), EXPOSURE_HEALTH_CHECKS)
return [
@@ -376,7 +372,7 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
total_exposures=total_exposures,
multiple_variant_handling=multiple_variant_handling,
sample_ratio_mismatch_p_value=sample_ratio_mismatch.p_value if sample_ratio_mismatch else None,
- hours_since_launch=self._hours_since_launch(),
+ hours_since_launch=self.experiment.hours_since_launch,
)
)
diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.py
index 2cf9350f28ca..c4e22e0812f0 100644
--- a/products/experiments/backend/models/experiment.py
+++ b/products/experiments/backend/models/experiment.py
@@ -194,6 +194,13 @@ class Experiment(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixi
def is_stopped(self) -> bool:
return self.is_launched and self.end_date is not None
+ @property
+ def hours_since_launch(self) -> float | None:
+ # Counts to now also after the end date.
+ if self.start_date is None:
+ return None
+ return (timezone.now() - self.start_date).total_seconds() / 3600
+
@property
def is_paused(self) -> bool:
# Pause is not stored on the experiment — it is the running state with the linked flag deactivated.
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 675dfa204c2b..4c41fdd43b5f 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -353,9 +353,8 @@ def _capture_results_refresh_completed(update: RecalculationProgressUpdate) -> N
)
# Hours since the experiment launched, matching the legacy frontend definition exactly
# (now - start_date, ignoring end_date) so dashboards can share the >12h filter across paths.
- experiment_duration_hours = (
- round((timezone.now() - experiment.start_date).total_seconds() / 3600) if experiment.start_date else None
- )
+ hours_since_launch = experiment.hours_since_launch
+ experiment_duration_hours = round(hours_since_launch) if hours_since_launch is not None else None
# Count from the discovery list that also sets total_metrics, so saved metrics count and legacy
# metrics that the run never calculates do not.
roles = [metric.metric_type for metric in discover_experiment_metrics(experiment)]
diff --git a/products/feature_flags/backend/blast_radius_flag_deps.py b/products/feature_flags/backend/blast_radius_flag_deps.py
index ec6120aac7b0..ae3869feb15b 100644
--- a/products/feature_flags/backend/blast_radius_flag_deps.py
+++ b/products/feature_flags/backend/blast_radius_flag_deps.py
@@ -18,7 +18,12 @@ from posthog.models.team.team import Team
from posthog.utils import safe_int
from products.feature_flags.backend.facade.config import detect_config_format
-from products.feature_flags.backend.facade.filters import EVALUATED_BEFORE_RELEASE_CONDITIONS
+from products.feature_flags.backend.facade.filters import (
+ EVALUATED_BEFORE_RELEASE_CONDITIONS,
+ condition_aggregation,
+ condition_rollout_percentage,
+ pinned_variant,
+)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
# Neither the flags service nor the save path limits how deep a dependency chain goes, so the
@@ -203,11 +208,11 @@ class FlagDependencyEstimator:
matches the person and its rollout admits them. None when a set cannot be sized per person.
"""
admitted: list[ast.Expr] = []
+ flag_aggregation = flag.aggregation_group_type_index
for condition in flag.conditions:
- if _is_group_aggregated(flag, condition):
+ if condition_aggregation(condition, flag_aggregation) is not None:
return None
- rollout_percentage = condition.get("rollout_percentage")
- rollout = 1.0 if rollout_percentage is None else float(rollout_percentage) / 100
+ rollout = float(condition_rollout_percentage(condition)) / 100
factors: list[ast.Expr] = [ast.Constant(value=rollout)]
properties = condition.get("properties") or []
@@ -234,8 +239,8 @@ class FlagDependencyEstimator:
terms: list[ast.Expr] = []
for index, condition in enumerate(flag.conditions):
- pinned = condition.get("variant")
- if pinned in variant_keys:
+ pinned = pinned_variant(condition, variant_keys)
+ if pinned is not None:
share = 1.0 if pinned == variant else 0.0
else:
share = hashed_variant_share
@@ -350,12 +355,6 @@ def _has_unmodeled_evaluation(flag: FeatureFlag) -> bool:
return any(filters.get(key) for key in _UNMODELED_FILTER_KEYS)
-def _is_group_aggregated(flag: FeatureFlag, condition: dict[str, Any]) -> bool:
- if "aggregation_group_type_index" in condition:
- return condition["aggregation_group_type_index"] is not None
- return flag.aggregation_group_type_index is not None
-
-
def _running_max(exprs: list[ast.Expr]) -> ast.Expr:
# A flat array rather than nested greatest() calls, so a flag with hundreds of sets does not
# exhaust the recursion limit in the visitors and the printer.
diff --git a/products/feature_flags/backend/facade/filters.py b/products/feature_flags/backend/facade/filters.py
index 858d616c1807..dd747e7893c0 100644
--- a/products/feature_flags/backend/facade/filters.py
+++ b/products/feature_flags/backend/facade/filters.py
@@ -8,15 +8,18 @@ learns no consumer concepts.
Every transform and predicate reads config version 1 keys, so each one raises
``ConfigFormatError`` for a document in any other format before it reads or copies
-anything: a v2 document must never silently gain v1 keys here.
+anything: a v2 document must never silently gain v1 keys here. The readers of release
+conditions take the values that the ``FeatureFlag`` accessors return, and those accessors
+refuse a document in another format.
Deliberately free of Django/DRF imports: consumer model modules import these predicates
at module level, and routing them through ``facade.api`` (which imports the flag
serializer, whose module imports back into consumers) would create an import cycle.
"""
+from collections.abc import Collection, Mapping, Sequence
from copy import deepcopy
-from typing import Literal
+from typing import Any, Literal
from products.feature_flags.backend.facade.config import require_v1_config
@@ -30,6 +33,75 @@ EVALUATED_BEFORE_RELEASE_CONDITIONS: frozenset[str] = frozenset(
)
+def condition_rollout_percentage(condition: Mapping[str, Any]) -> int | float:
+ """The rollout of a release condition. An absent or null value reads as 100, as
+ ``rollout_percentage_unwrapped`` in ``rust/feature-flags/src/flags/flag_property_group.rs``.
+
+ The value is returned as stored, without a conversion to float. The stale-flags health check
+ writes it into its evidence, so a conversion would change a stored 100 to 100.0 there.
+ """
+ rollout_percentage = condition.get("rollout_percentage")
+ return 100 if rollout_percentage is None else rollout_percentage
+
+
+def condition_aggregation(condition: Mapping[str, Any], flag_aggregation: int | None) -> int | None:
+ """The group type index a release condition aggregates on, or None for person aggregation.
+
+ An absent key falls back to the flag-level value and an explicit null means person
+ aggregation, the same as ``effective_aggregation`` in
+ ``rust/feature-flags/src/flags/flag_property_group.rs``.
+ """
+ if "aggregation_group_type_index" in condition:
+ return condition.get("aggregation_group_type_index")
+ return flag_aggregation
+
+
+def pinned_variant(condition: Mapping[str, Any], variant_keys: Collection[str]) -> str | None:
+ """The variant a release condition serves to every user it matches, or None when the hash picks one.
+
+ The flag service ignores an override that names no variant of the flag, as ``pinned_variant``
+ in ``rust/feature-flags/src/flags/flag_operations.rs``.
+ """
+ variant = condition.get("variant")
+ return variant if variant is not None and variant in variant_keys else None
+
+
+def reachable_conditions(
+ conditions: Sequence[Mapping[str, Any]], *, flag_aggregation: int | None, early_exit: bool
+) -> tuple[int, ...]:
+ """The indexes of the release conditions that can serve a request, in evaluation order.
+
+ The flag service reads the conditions in stored order and stops at the first match, see
+ ``get_match`` in ``rust/feature-flags/src/flags/flag_matching.rs``. A condition at 0% serves
+ nobody. A condition without properties matches every request that reaches it, so at a full
+ rollout the evaluation ends there. With ``early_exit`` the evaluation also ends at a lower
+ rollout, 0% included, because a request outside the rollout gets no match instead of the next
+ condition.
+
+ A request without a group's key skips the conditions of that group type. A group condition
+ without properties therefore ends the evaluation only for the requests of its group type, and
+ a person condition without properties ends it for every request.
+
+ Not modeled: with device-id bucketing, a request without a device id skips each person
+ condition whose result depends on the hash, so it can reach conditions after a person
+ condition without properties.
+ """
+ ended_group_types: set[int] = set()
+ reachable: list[int] = []
+ for index, condition in enumerate(conditions):
+ group_type = condition_aggregation(condition, flag_aggregation)
+ if group_type in ended_group_types:
+ continue
+ rollout = condition_rollout_percentage(condition)
+ if rollout > 0:
+ reachable.append(index)
+ if not condition.get("properties") and (rollout >= 100 or early_exit):
+ if group_type is None:
+ break
+ ended_group_types.add(group_type)
+ return tuple(reachable)
+
+
def restrict_groups_to_cohort(
current_filters: dict,
cohort_id: int,
@@ -254,11 +326,10 @@ def _leads_with_unconditional_rollout(current_filters: dict) -> bool:
first = groups[0]
if first.get("properties") or first.get("variant"):
return False
- rollout_percentage = first.get("rollout_percentage")
- if rollout_percentage is not None and rollout_percentage != 100:
+ if condition_rollout_percentage(first) != 100:
return False
flag_aggregation = current_filters.get("aggregation_group_type_index")
- return first.get("aggregation_group_type_index", flag_aggregation) == flag_aggregation
+ return condition_aggregation(first, flag_aggregation) == flag_aggregation
def roll_out_to_everyone(current_filters: dict, *, variant_key: str | None = None) -> dict:
diff --git a/products/feature_flags/backend/flag_status.py b/products/feature_flags/backend/flag_status.py
index 9306baae5b76..908e38067bd0 100644
--- a/products/feature_flags/backend/flag_status.py
+++ b/products/feature_flags/backend/flag_status.py
@@ -8,6 +8,7 @@ import structlog
from posthog.dataclasses import frozen
from .facade.config import ConfigFormatError
+from .facade.filters import condition_aggregation, condition_rollout_percentage, pinned_variant
from .models.feature_flag import FeatureFlag
logger = structlog.get_logger(__name__)
@@ -292,18 +293,6 @@ def _sole_reachable_variant(variants: list[dict]) -> str | None:
return None
-def _condition_aggregation(flag_level_index: int | None, group: dict) -> int | None:
- """The group type index a condition aggregates on, or None for person aggregation.
-
- An absent key falls back to the flag-level value and an explicit null means person
- aggregation, the same as `effective_aggregation` in
- `rust/feature-flags/src/flags/flag_property_group.rs`.
- """
- if "aggregation_group_type_index" in group:
- return group.get("aggregation_group_type_index")
- return flag_level_index
-
-
# FeatureFlagStatusChecker is used to determine the status of a feature flag for a given user.
# Eventually, this may be used to automatically archive old flags that are no longer in use.
#
@@ -421,8 +410,7 @@ class FeatureFlagStatusChecker:
# A missing rollout_percentage evaluates to 100% at runtime, so it counts as 100 here.
# This is deliberately looser than effectively_full_rollout / is_group_fully_rolled_out,
# which require an explicit 100.
- percentage = group.get("rollout_percentage")
- percentage = 100 if percentage is None else percentage
+ percentage = condition_rollout_percentage(group)
max_rollout_percentage = (
percentage if max_rollout_percentage is None else max(max_rollout_percentage, percentage)
)
@@ -497,14 +485,12 @@ class FeatureFlagStatusChecker:
variant_keys = {variant.get("key") for variant in variants}
results = set()
for group in groups[: decider + 1]:
- # A missing rollout_percentage evaluates to 100% at runtime, matching `get_rollout_summary`.
- percentage = group.get("rollout_percentage")
- if percentage is not None and percentage <= 0:
+ if condition_rollout_percentage(group) <= 0:
continue
# The matcher ignores an override naming a variant the flag does not configure, and the
# distribution decides instead.
- override = group.get("variant")
- results.add(override if override in variant_keys else distributed)
+ override = pinned_variant(group, variant_keys)
+ results.add(distributed if override is None else override)
# `None` is in the set when a path falls through to a distribution that is not itself constant.
if len(results) != 1:
return None
@@ -530,13 +516,13 @@ class FeatureFlagStatusChecker:
"""
groups = flag.conditions
flag_level_index = flag.aggregation_group_type_index
- mixed = len({_condition_aggregation(flag_level_index, group) for group in groups}) > 1
+ mixed = len({condition_aggregation(group, flag_level_index) for group in groups}) > 1
return next(
(
index
for index, group in enumerate(groups)
if self.is_group_fully_rolled_out(group)
- and (not mixed or _condition_aggregation(flag_level_index, group) is None)
+ and (not mixed or condition_aggregation(group, flag_level_index) is None)
),
None,
)
diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.py
index f610e91b2f62..10754d1461f1 100644
--- a/products/feature_flags/backend/test/test_facade.py
+++ b/products/feature_flags/backend/test/test_facade.py
@@ -32,6 +32,7 @@ from products.feature_flags.backend.facade.filters import (
_leads_with_unconditional_rollout,
group_cohort_restriction_blocker,
groups_carry_restriction_marker,
+ reachable_conditions,
replace_release_conditions,
replace_variant_distribution,
restrict_groups_to_cohort,
@@ -934,6 +935,46 @@ class TestReleaseConditionTransforms:
assert filters["groups"][0]["properties"][0]["key"] == "old" # input not mutated
+EVERYONE: dict[str, Any] = {"properties": [], "rollout_percentage": 100}
+STAFF: dict[str, Any] = {
+ "properties": [{"key": "email", "value": "@example.com", "operator": "icontains", "type": "person"}],
+ "rollout_percentage": 100,
+}
+
+
+class TestReachableConditions:
+ @parameterized.expand(
+ [
+ ("person_catch_all_ends_the_evaluation", [EVERYONE, STAFF], False, (0,)),
+ ("absent_rollout_reads_as_full", [{"properties": []}, STAFF], False, (0,)),
+ ("condition_at_zero_serves_nobody", [{**STAFF, "rollout_percentage": 0}, EVERYONE], False, (1,)),
+ ("partial_catch_all_continues", [{**EVERYONE, "rollout_percentage": 50}, STAFF], False, (0, 1)),
+ ("partial_catch_all_ends_with_early_exit", [{**EVERYONE, "rollout_percentage": 50}, STAFF], True, (0,)),
+ ("zero_catch_all_ends_with_early_exit", [{**EVERYONE, "rollout_percentage": 0}, EVERYONE], True, ()),
+ (
+ "group_catch_all_ends_only_its_group_type",
+ [{**EVERYONE, "aggregation_group_type_index": 0}, STAFF],
+ False,
+ (0, 1),
+ ),
+ (
+ "condition_of_an_ended_group_type_is_skipped",
+ [
+ {**EVERYONE, "aggregation_group_type_index": 0},
+ {**EVERYONE, "aggregation_group_type_index": 0},
+ STAFF,
+ ],
+ False,
+ (0, 2),
+ ),
+ ]
+ )
+ def test_reachable_conditions(
+ self, _name: str, conditions: list[dict[str, Any]], early_exit: bool, expected: tuple[int, ...]
+ ) -> None:
+ assert reachable_conditions(conditions, flag_aggregation=None, early_exit=early_exit) == expected
+
+
class TestExperimentRuleFromFilters:
@parameterized.expand(
[