: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(flags): move flag edit primitives to the flags facade (#121683)
Gustavo H. Strassburgerfbc7b8a244e0
diff --git a/products/experiments/backend/health/bucketing_changes.py b/products/experiments/backend/health/bucketing_changes.pyindex ab9a32d48334..70223c783cbc 100644--- a/products/experiments/backend/health/bucketing_changes.py+++ b/products/experiments/backend/health/bucketing_changes.py@@ -1,22 +1,14 @@"""Changes of the flag settings besides the split that decide a person's variant draw, read from the flag's activity-log. Pure functions, no I/O.--The flag service hashes the flag key with an identifier: the group key for a flag that aggregates by a group type,-otherwise the device ID or the distinct ID, as `bucketing_identifier` says, and with experience continuity the-person's stored anonymous ID (`hashed_identifier` in rust/feature-flags/src/flags/flag_matching.rs). A change of any-of them gives the people it touches a new draw, so they can get another variant.+log. Pure functions, no I/O. The flags facade (`facade/edits.py`) owns how the flag service reads each setting."""-from collections.abc import Mapping, Sequence-from datetime import datetime+from collections.abc import Sequencefrom enum import StrEnum-from itertools import groupbyfrom posthog.dataclasses import frozen-from products.experiments.backend.health.context import BucketingChange, BucketingSetting-from products.feature_flags.backend.facade.filters import condition_aggregation+from products.feature_flags.backend.facade.edits import BucketingChange, BucketingSettingclass BucketingChangeShape(StrEnum):@@ -50,100 +42,6 @@ class BucketingNetEffect:change_count: int-def bucketing_changes_from_activity(- *,- changed_at: datetime,- feature_flag_id: int,- before: Mapping[BucketingSetting, object],- after: Mapping[BucketingSetting, object],-) -> list[BucketingChange]:- """The bucketing changes in one activity log row of the flag. A setting the row does not change is absent."""- changes = []- for setting in BucketingSetting:- value_before = _normalized(setting, before.get(setting), feature_flag_id)- value_after = _normalized(setting, after.get(setting), feature_flag_id)- if value_before != value_after:- changes.append(- BucketingChange(changed_at=changed_at, setting=setting, before=value_before, after=value_after)- )- return changes---def conditions_follow_flag_aggregation(aggregation: object, conditions: Sequence[object]) -> bool:- """- Whether no release condition aggregates by person while the flag-level aggregation names a group type.- `changes_that_apply` relies on this, because it reads only the flag-level aggregation of each save. The flag- serializer keeps it true: it sets the flag-level aggregation to null when the conditions mix aggregations.- """- flag_aggregation = _group_type_index(aggregation)- return flag_aggregation is None or all(- condition_aggregation(condition, flag_aggregation) is not None- for condition in conditions- if isinstance(condition, dict)- )---def changes_that_apply(- changes: Sequence[BucketingChange],- *,- feature_flag_id: int,- aggregation: object,- bucketing_identifier: object,- trust_flag_aggregation: bool,-) -> tuple[BucketingChange, ...]:- """- The changes as the flag service reads them, save by save. It hashes the group key for a flag that aggregates by- a group type, so it does not read the bucketing identifier and persistence there. It hashes the device ID before- it reads persistence, so it does not read persistence under device ID bucketing either.-- A setting that changes while the flag service does not read it moves nobody at that save. The new value takes- effect at the save after which the flag service reads the setting again, so the change counts there, from the- value that the flag service read last.-- `aggregation` and `bucketing_identifier` are the flag's current values. When `trust_flag_aggregation` is false,- a release condition can aggregate by person under any flag-level aggregation, so the flag-level aggregation does- not stop the flag service from reading the identifier.- """- state: dict[BucketingSetting, str | int | bool | None] = {- BucketingSetting.AGGREGATION: _normalized(BucketingSetting.AGGREGATION, aggregation, feature_flag_id),- BucketingSetting.BUCKETING_IDENTIFIER: _normalized(- BucketingSetting.BUCKETING_IDENTIFIER, bucketing_identifier, feature_flag_id- ),- }- # Each setting holds the `before` of its first change until that change, and its current value without one.- for change in reversed(changes):- state[change.setting] = change.before-- def reads(setting: BucketingSetting) -> bool:- by_person = state[BucketingSetting.AGGREGATION] is None or not trust_flag_aggregation- match setting:- case BucketingSetting.BUCKETING_IDENTIFIER:- return by_person- case BucketingSetting.EXPERIENCE_CONTINUITY:- return by_person and state[BucketingSetting.BUCKETING_IDENTIFIER] == "distinct_id"- case _:- return True-- last_read = {setting: value for setting, value in state.items() if reads(setting)}- applied = []- for changed_at, saved in groupby(changes, key=lambda change: change.changed_at):- for change in saved:- state[change.setting] = change.after- for setting in BucketingSetting:- if setting not in state or not reads(setting):- continue- # A setting that the flag service never read before has no earlier value to count from. The change- # that made the flag service read it, such as an aggregation change, counts instead.- if setting in last_read and last_read[setting] != state[setting]:- applied.append(- BucketingChange(- changed_at=changed_at, setting=setting, before=last_read[setting], after=state[setting]- )- )- last_read[setting] = state[setting]- return tuple(applied)--def bucketing_net_effect(changes: Sequence[BucketingChange]) -> BucketingNetEffect | None:if not changes:return None@@ -184,26 +82,3 @@ def describe_bucketing_value(setting: BucketingSetting, value: str | int | boolreturn "device ID" if value == "device_id" else "user ID"case BucketingSetting.EXPERIENCE_CONTINUITY:return "on" if value else "off"---def _normalized(setting: BucketingSetting, value: object, feature_flag_id: int) -> str | int | bool | None:- # Each setting is read the way the flag service reads it, so a save that writes the default explicitly is- # no change.- match setting:- case BucketingSetting.KEY:- if not isinstance(value, str):- return None- # Deleting a flag that an experiment uses appends this suffix to its key (`FeatureFlag.tombstoned_key`),- # and restoring it removes the suffix again. Neither is a new key.- tombstone = f":deleted:{feature_flag_id}"- return value.removesuffix(tombstone)- case BucketingSetting.AGGREGATION:- return _group_type_index(value)- case BucketingSetting.BUCKETING_IDENTIFIER:- return "device_id" if value == "device_id" else "distinct_id"- case BucketingSetting.EXPERIENCE_CONTINUITY:- return value is True---def _group_type_index(value: object) -> int | None:- return value if isinstance(value, int) and not isinstance(value, bool) else Nonediff --git a/products/experiments/backend/health/checks/bucketing_changed.py b/products/experiments/backend/health/checks/bucketing_changed.pyindex f93ac065d319..09d15fd71c61 100644--- a/products/experiments/backend/health/checks/bucketing_changed.py+++ b/products/experiments/backend/health/checks/bucketing_changed.py@@ -30,14 +30,9 @@ from products.experiments.backend.health.checks.flag_change_findings import (leave_out,not_checked_finding,)-from products.experiments.backend.health.context import (- BucketingChange,- BucketingSetting,- FlagHistory,- FlagHistoryNotChecked,- HealthContext,-)+from products.experiments.backend.health.context import FlagHistory, FlagHistoryNotChecked, HealthContextfrom products.experiments.backend.health.split_changes import format_change_time+from products.feature_flags.backend.facade.edits import BucketingChange, BucketingSetting_TITLE = "The flag's variant assignment changed after launch"_KEY_TITLE = "The flag key changed after launch"diff --git a/products/experiments/backend/health/checks/conditions_changed.py b/products/experiments/backend/health/checks/conditions_changed.pyindex 58e961eb2e58..1f9e2bc787b9 100644--- a/products/experiments/backend/health/checks/conditions_changed.py+++ b/products/experiments/backend/health/checks/conditions_changed.py@@ -37,7 +37,6 @@ from products.experiments.backend.health.condition_changes import (conditions_net_effect,)from products.experiments.backend.health.context import (- ConditionsChange,FlagHistory,FlagHistoryNotChecked,HealthContext,@@ -53,6 +52,7 @@ from products.experiments.backend.health.pinned_share import (pinned_share_severity,)from products.experiments.backend.health.split_changes import format_change_time+from products.feature_flags.backend.facade.edits import ConditionsChange_TITLE = "The release conditions changed after launch"_OVERRIDE_TITLE = "A variant override was removed after launch"diff --git a/products/experiments/backend/health/checks/flag_state.py b/products/experiments/backend/health/checks/flag_state.pyindex d357fb6383bb..1b6b022511a5 100644--- a/products/experiments/backend/health/checks/flag_state.py+++ b/products/experiments/backend/health/checks/flag_state.py@@ -27,7 +27,6 @@ from products.experiments.backend.health.context import (FlagState,HealthContext,PauseHistory,- SplitChange,)from products.experiments.backend.health.skips import NO_FLAG, CheckSkip, not_applicablefrom products.experiments.backend.health.split_changes import (@@ -36,6 +35,7 @@ from products.experiments.backend.health.split_changes import (format_change_time,net_effect,)+from products.feature_flags.backend.facade.edits import SplitChange# pinned: the page's warning keys. The page sends them as `finding_variant` and# `warning_key` on its events, and picks the banner text by them.diff --git a/products/experiments/backend/health/checks/forced_variant.py b/products/experiments/backend/health/checks/forced_variant.pyindex 004eceeb8305..f938a1758f2c 100644--- a/products/experiments/backend/health/checks/forced_variant.py+++ b/products/experiments/backend/health/checks/forced_variant.py@@ -20,13 +20,7 @@ from products.experiments.backend.facade.contracts import ()from products.experiments.backend.health.checks.flag_state import is_single_variant_shipped, shipped_variant_keyfrom products.experiments.backend.health.condition_changes import conditions_net_effect-from products.experiments.backend.health.context import (- ConditionsChange,- FlagHistory,- HealthContext,- ReachableCondition,- VariantProperty,-)+from products.experiments.backend.health.context import FlagHistory, HealthContext, ReachableCondition, VariantPropertyfrom products.experiments.backend.health.pinned_share import (PinnedConditions,PinnedShareGrade,@@ -37,6 +31,7 @@ from products.experiments.backend.health.pinned_share import ()from products.experiments.backend.health.skips import CheckSkip, flag_setup_skipfrom products.experiments.backend.health.split_changes import format_change_time+from products.feature_flags.backend.facade.edits import ConditionsChange# 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 getsdiff --git a/products/experiments/backend/health/checks/split_changed.py b/products/experiments/backend/health/checks/split_changed.pyindex 8d60158c2d6c..e6302d7c418e 100644--- a/products/experiments/backend/health/checks/split_changed.py+++ b/products/experiments/backend/health/checks/split_changed.py@@ -27,20 +27,17 @@ from products.experiments.backend.health.checks.flag_change_findings import (not_checked_finding,)from products.experiments.backend.health.checks.flag_state import is_single_variant_shipped-from products.experiments.backend.health.context import (- FlagHistory,- FlagHistoryNotChecked,- FlagState,- HealthContext,- SplitChange,-)+from products.experiments.backend.health.context import FlagHistory, FlagHistoryNotChecked, FlagState, HealthContextfrom products.experiments.backend.health.split_changes import (SplitChangeShape,SplitNetEffect,- added_variant_keys,describe_split,format_change_time,net_effect,+)+from products.feature_flags.backend.facade.edits import (+ SplitChange,+ added_variant_keys,removed_variant_keys,rolled_out_variant_key,zeroed_variant_keys,diff --git a/products/experiments/backend/health/condition_changes.py b/products/experiments/backend/health/condition_changes.pyindex 2ef19ee56e2d..472431226955 100644--- a/products/experiments/backend/health/condition_changes.py+++ b/products/experiments/backend/health/condition_changes.py@@ -1,12 +1,8 @@"""Changes of the flag's release conditions, read from the flag's activity log. Pure functions, no I/O.-A condition whose criteria change, or a condition that is added or removed, moves people into or out of the flag,-never to another variant (`get_match` in rust/feature-flags/src/flags/flag_matching.rs). A variant override does-move people: everyone a condition with an override matches gets that variant instead of the one from the hash.-The flag service evaluates the conditions in order, so the order moves people who match two conditions that serve-different variants. A rollout change alone moves people in or out too, but an increase is harmless, so it is not a-change here.+The flags facade (`facade/edits.py`) owns which condition changes move people to another variant. A rollout change+alone moves people in or out too, but an increase is harmless, so it is not a change here.Each change pairs the conditions before it with the conditions after it, as the flag page's history does, so anoverride stays with its condition when the filters of that condition change.@@ -15,23 +11,27 @@ An override set after launch that is still in place is the forced-variant check'set. An override that is gone leaves no state to report, so the release-condition check reports it."""-import jsonimport itertools-from collections import deque-from collections.abc import Callable, Collection, Hashable, Iterator, Mapping, Sequence+from collections.abc import Iterator, Mapping, Sequencefrom dataclasses import replacefrom datetime import datetimefrom enum import StrEnumfrom posthog.dataclasses import frozen-from products.experiments.backend.health.context import ChangeWindow, ConditionsChange, ReleaseCondition, parse_variants-from products.experiments.backend.health.split_changes import EXPOSURE_FREEZE_JOB_TYPES, split_variant_keys-from products.feature_flags.backend.facade.filters import condition_aggregation, pinned_variant--ReleaseConditions = tuple[ReleaseCondition, ...]-_MAX_LOOK_ALIKES = 100-_FOLLOWS_FLAG_AGGREGATION = "flag"+from products.experiments.backend.health.context import ChangeWindow+from products.experiments.backend.health.split_changes import EXPOSURE_FREEZE_JOB_TYPES+from products.feature_flags.backend.facade.edits import (+ ConditionsChange,+ ReleaseCondition,+ ReleaseConditions,+ moves_people,+ order_moves_people,+ pair_conditions,+ parse_release_conditions,+ parse_variants,+ split_variant_keys,+)class ConditionsChangeShape(StrEnum):@@ -132,73 +132,10 @@ def conditions_change_from_activity(return ConditionsChange(changed_at=changed_at, before=before, after=after)-def parse_release_conditions(- groups: object, *, flag_aggregation: object = None, variant_keys: Collection[str]-) -> ReleaseConditions:- """`variant_keys` are the variants of the flag in the same version, because the flag service ignores an- override that names no variant of the flag."""- aggregation = _group_type_index(flag_aggregation)- return tuple(_condition(group, aggregation, variant_keys) for group in groups) if isinstance(groups, list) else ()--def conditions_shape(before: ReleaseConditions, after: ReleaseConditions) -> ConditionsChangeShape | None:"""What changed between two sets of release conditions, or None when they match the same people and servethem the same variants. The first match wins."""- return _shape(before, after, _pair_conditions(before, after))---def _pair_conditions(before: ReleaseConditions, after: ReleaseConditions) -> dict[int, int]:- """- The condition that each condition after a change was before it, as indexes from `after` to `before`. A- condition without a pair was added or removed. The pairing is the one of the flag page's history- (`diffReleaseConditionSets` in releaseConditionsDiff.ts): an unchanged condition first, then one with the same- criteria, then a look-alike at the same position, then the only look-alike left.- """- pairs: dict[int, int] = {}- paired: set[int] = set()-- def pair(after_index: int, before_index: int) -> None:- pairs[after_index] = before_index- paired.add(before_index)-- def pair_first_with_same(key: Callable[[ReleaseCondition], Hashable]) -> None:- waiting: dict[Hashable, deque[int]] = {}- for index, old in enumerate(before):- if index not in paired:- waiting.setdefault(key(old), deque()).append(index)- for after_index, condition in enumerate(after):- candidates = waiting.get(key(condition))- if after_index not in pairs and candidates:- pair(after_index, candidates.popleft())-- pair_first_with_same(lambda condition: condition)- pair_first_with_same(lambda condition: condition.criteria)- unpaired_after = [index for index in range(len(after)) if index not in pairs]- unpaired_before = [index for index in range(len(before)) if index not in paired]- # Look-alikes are compared each with each. A save that edits more conditions than this pairs no more of them,- # so they count as removed and added, which bounds the work for a flag with very many conditions.- if len(unpaired_after) > _MAX_LOOK_ALIKES or len(unpaired_before) > _MAX_LOOK_ALIKES:- return pairs- for after_index in unpaired_after:- if (- after_index < len(before)- and after_index not in paired- and _looks_alike(before[after_index], after[after_index])- ):- pair(after_index, after_index)- # A condition that was edited and moved in one save has no partner at its position. It pairs with the one- # condition left that it looks like. With several, no pair is safe, so they count as removed and added.- for after_index in unpaired_after:- if after_index in pairs:- continue- candidates = [- index- for index in unpaired_before- if index not in paired and _looks_alike(before[index], after[after_index])- ]- if len(candidates) == 1:- pair(after_index, candidates[0])- return pairs+ return _shape(before, after, pair_conditions(before, after))def conditions_net_effect(@@ -239,7 +176,7 @@ def conditions_net_effect(overrides=overrides,audience_changed=_criteria_without(first.before, followed.start_ids, touched)!= _criteria_without(last.after, followed.end_ids, touched),- reordered=_reordered(first.before, last.after, net_pairs),+ reordered=order_moves_people(first.before, last.after, net_pairs),edited_overrides=tuple(EditedOverride(variant=variant, condition_number=numbers[condition_id])for end_index, start_index in sorted(net_pairs.items())@@ -287,7 +224,7 @@ def _follow(changes: Sequence[ConditionsChange]) -> _Followed:after = dict(zip(after_ids, change.after))for condition_id in dict.fromkeys([*before_ids, *after_ids]):old, new = before.get(condition_id), after.get(condition_id)- if _moves_people(old, new):+ if moves_people(old, new):variant_changes.append(_VariantChange(condition_id=condition_id,@@ -307,7 +244,7 @@ def _rejoin(followed: _Followed, start: ReleaseConditions, end: ReleaseConditionstart_ids, end_ids = set(followed.start_ids), set(followed.end_ids)gone = [index for index, condition_id in enumerate(followed.start_ids) if condition_id not in end_ids]new = [index for index, condition_id in enumerate(followed.end_ids) if condition_id not in start_ids]- pairs = _pair_conditions(tuple(start[index] for index in gone), tuple(end[index] for index in new))+ pairs = pair_conditions(tuple(start[index] for index in gone), tuple(end[index] for index in new))joined = {followed.end_ids[new[new_index]]: followed.start_ids[gone[gone_index]]for new_index, gone_index in pairs.items()@@ -330,7 +267,7 @@ def _next_id(followed: _Followed) -> int:def _carry_ids(before: ReleaseConditions, ids: tuple[int, ...], after: ReleaseConditions, new_ids: Iterator[int]) -> tuple[int, ...]:- pairs = _pair_conditions(before, after)+ pairs = pair_conditions(before, after)return tuple(ids[pairs[index]] if index in pairs else next(new_ids) for index in range(len(after)))@@ -410,7 +347,7 @@ def _shape(*((condition, None) for index, condition in enumerate(before) if index not in paired),*((None, condition) for index, condition in enumerate(after) if index not in pairs),]- if any(_moves_people(old, new) for old, new in sides) or _reordered(before, after, pairs):+ if any(moves_people(old, new) for old, new in sides) or order_moves_people(before, after, pairs):return ConditionsChangeShape.VARIANT_OVERRIDE_CHANGED# When no variant moves, the order does not decide who is in the flag.if sorted(condition.criteria for condition in before) != sorted(condition.criteria for condition in after):@@ -418,39 +355,6 @@ def _shape(return None-def _moves_people(before: ReleaseCondition | None, after: ReleaseCondition | None) -> bool:- # A condition at 0% rollout serves nobody, so its override moves nobody.- return _variant(before) != _variant(after) and any(- condition is not None and condition.rollout > 0 for condition in (before, after)- )---def _reordered(before: ReleaseConditions, after: ReleaseConditions, pairs: Mapping[int, int]) -> bool:- # A person who matches two conditions gets the variant of the first one, the override or the hash's. Walking- # the conditions in their new order, a condition moved ahead of one with another variant when that one sat- # later before the change. Keeping the latest position and the latest of any other variant finds it in one pass.- latest: tuple[int, str | None] | None = None- latest_of_other_variant = -1- for after_index, before_index in sorted(pairs.items()):- if before[before_index].rollout <= 0 or after[after_index].rollout <= 0:- continue- variant = after[after_index].variant- if latest is not None:- latest_position, latest_variant = latest- if (latest_position if latest_variant != variant else latest_of_other_variant) > before_index:- return True- if variant == latest_variant:- latest = (max(latest_position, before_index), variant)- elif before_index > latest_position:- latest_of_other_variant = latest_position- latest = (before_index, variant)- else:- latest_of_other_variant = max(latest_of_other_variant, before_index)- else:- latest = (before_index, variant)- return False--def _criteria_without(conditions: ReleaseConditions, ids: tuple[int, ...], touched: set[int]) -> list[str]:return sorted(condition.criteria for condition, condition_id in zip(conditions, ids) if condition_id not in touched)@@ -461,68 +365,3 @@ def _variant(condition: ReleaseCondition | None) -> str | None:def _audience(condition: ReleaseCondition) -> tuple[str, float]:return condition.criteria, condition.rollout---def _looks_alike(old: ReleaseCondition, new: ReleaseCondition) -> bool:- # Two conditions look alike when they match the same kind of thing: the same group type, and a shared property- # key or no properties on either. Otherwise an unrelated new condition would read as an edit.- if old.aggregation != new.aggregation:- return False- if not old.property_keys and not new.property_keys:- return True- return bool(old.property_keys & new.property_keys)---def _condition(group: object, flag_aggregation: int | None, variant_keys: Collection[str]) -> ReleaseCondition:- if not isinstance(group, dict):- return ReleaseCondition(- criteria=json.dumps(group, sort_keys=True, default=str),- aggregation=None,- property_keys=frozenset(),- rollout=100,- variant=None,- )- properties = group.get("properties")- rollout = group.get("rollout_percentage")- aggregation = condition_aggregation(group, flag_aggregation)- return ReleaseCondition(- criteria=json.dumps(- [- # A change of the flag-level aggregation is the bucketing check's to report, so a condition that- # follows it keeps its criteria.- _FOLLOWS_FLAG_AGGREGATION if aggregation == flag_aggregation else aggregation,- # The filters of a condition all have to match, so their order does not matter.- sorted(_property_signature(prop) for prop in properties) if isinstance(properties, list) else None,- ],- sort_keys=True,- default=str,- ),- aggregation=_group_type_index(aggregation),- property_keys=frozenset(_property_key(prop) for prop in properties)- if isinstance(properties, list)- else frozenset(),- # The flag service reads a missing rollout as 100%.- rollout=rollout if isinstance(rollout, int | float) and not isinstance(rollout, bool) else 100,- variant=pinned_variant(group, variant_keys),- )---def _property_signature(prop: object) -> str:- # The fields that decide a match, as the flag page's history compares them (releaseConditionsDiff.ts).- if not isinstance(prop, dict):- return json.dumps(prop, sort_keys=True, default=str)- return json.dumps(- [prop.get(field) for field in ("type", "key", "operator", "value", "group_type_index")],- sort_keys=True,- default=str,- )---def _property_key(prop: object) -> str:- if not isinstance(prop, dict):- return json.dumps(prop, sort_keys=True, default=str)- return f"{prop.get('type') or ''}:{prop.get('key') or ''}"---def _group_type_index(value: object) -> int | None:- return value if isinstance(value, int) and not isinstance(value, bool) else Nonediff --git a/products/experiments/backend/health/context.py b/products/experiments/backend/health/context.pyindex 6d494794a708..c2008a737739 100644--- a/products/experiments/backend/health/context.py+++ b/products/experiments/backend/health/context.py@@ -32,68 +32,22 @@ from products.experiments.backend.metric_resolution import MetricRole, saved_metfrom products.experiments.backend.metric_utils import get_default_metric_titlefrom products.experiments.backend.metric_validation import defined_event_names, extract_entity_nodesfrom products.experiments.backend.models.experiment import Experiment, ExperimentToSavedMetric+from products.feature_flags.backend.facade.edits import (+ BucketingChange,+ ConditionsChange,+ FlagVariant,+ ReleaseCondition,+ SplitChange,+ parse_percentage,+ parse_variants,+)from products.feature_flags.backend.facade.enums import FlagEvaluationsModefrom products.feature_flags.backend.facade.filters import condition_aggregation, pinned_variant, reachable_conditionsfrom products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_mode, has_active_flags--@frozen-class FlagVariant:- key: str | None- rollout_percentage: float | None---Split = tuple[FlagVariant, ...]---@frozen-class SplitChange:- changed_at: datetime- before: Split- after: Split---class BucketingSetting(StrEnum):- # The flag settings besides the split that are inputs of the variant draw, in the order the findings name them.- KEY = "key"- AGGREGATION = "aggregation"- BUCKETING_IDENTIFIER = "bucketing_identifier"- EXPERIENCE_CONTINUITY = "experience_continuity"---@frozen-class BucketingChange:- changed_at: datetime- setting: BucketingSetting- # The key as a string, the aggregation as a group type index or None for persons, the identifier as- # "distinct_id" or "device_id", the continuity as a bool.- before: str | int | bool | None- after: str | int | bool | None---@frozen-class ReleaseCondition:- # The group type and property filters of the condition, as a signature that is equal for two conditions- # that match the same people under the flag-level aggregation of their save. The rollout is not part of it.- criteria: str- # The group type index that the condition matches, None for persons, and the keys of its property filters.- # The flag page's history pairs two conditions that share them as one condition edited.- aggregation: int | None- property_keys: frozenset[str]- rollout: float- variant: str | None---@frozen-class ConditionsChange:- changed_at: datetime- before: tuple[ReleaseCondition, ...]- after: tuple[ReleaseCondition, ...]---# A change of the flag after launch that can move exposed people. A new kind needs its class here, an-# `ExperimentHealthFlagChangeKind`, its read and its set-back question in `exposure_gate.py`, its row in-# `inputs_payload.py`, and its check.+# A change of the flag after launch that can move exposed people. A new kind needs its class in the flags facade+# (`facade/edits.py`), its member in this union, an `ExperimentHealthFlagChangeKind`, its read and its set-back+# question in `exposure_gate.py`, its row in `inputs_payload.py`, and its check.FlagChange = SplitChange | BucketingChange | ConditionsChange@@ -405,33 +359,11 @@ def _release_group(group: object) -> FlagReleaseGroup:return FlagReleaseGroup(rollout_percentage=None, property_count=None)properties = group.get("properties")return FlagReleaseGroup(- rollout_percentage=_percentage(group.get("rollout_percentage")),+ rollout_percentage=parse_percentage(group.get("rollout_percentage")),property_count=len(properties) if isinstance(properties, list) else None,)-def _variant(variant: object) -> FlagVariant:- if not isinstance(variant, dict):- return FlagVariant(key=None, rollout_percentage=None)- key = variant.get("key")- return FlagVariant(- key=key if isinstance(key, str) else None,- rollout_percentage=_percentage(variant.get("rollout_percentage")),- )---def parse_variants(variants: object) -> Split:- return tuple(_variant(variant) for variant in variants) if isinstance(variants, list) else ()---def _percentage(value: object) -> float | None:- # The page compares with `=== 0` and `=== 100`, so only a JSON number can match. A string or a- # boolean must not, and Python's `False == 0` would let a boolean through.- if isinstance(value, bool) or not isinstance(value, int | float):- return None- return float(value)--def _load_flag_state(experiment: Experiment) -> FlagState | None:# django-stubs types the id as int, but an unsaved instance can carry None.feature_flag_id: int | None = experiment.feature_flag_iddiff --git a/products/experiments/backend/health/exposure_gate.py b/products/experiments/backend/health/exposure_gate.pyindex f147c2b4d07f..12073243fdba 100644--- a/products/experiments/backend/health/exposure_gate.py+++ b/products/experiments/backend/health/exposure_gate.py@@ -51,41 +51,24 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models.activity_logging.activity_log import ActivityLogfrom products.experiments.backend.facade.contracts import ExperimentHealthFlagChangeKind, ExperimentHealthReaderAccess-from products.experiments.backend.health.bucketing_changes import (- BucketingChangeShape,- bucketing_changes_from_activity,- bucketing_net_effect,- changes_that_apply,- conditions_follow_flag_aggregation,-)+from products.experiments.backend.health.bucketing_changes import BucketingChangeShape, bucketing_net_effectfrom products.experiments.backend.health.condition_changes import (ConditionsChangeShape,conditions_change_from_activity,conditions_net_effect,- parse_release_conditions,)from products.experiments.backend.health.context import (MAX_FLAG_SAVES,MAX_RELEASE_CONDITIONS,MIN_EXPOSED_UNITS_TO_WARN,- BucketingChange,- BucketingSetting,ChangeWindow,- ConditionsChange,FlagChange,FlagHistory,FlagHistoryNotChecked,FlagHistoryNotCheckedReason,- Split,- SplitChange,changes_of_kind,- parse_variants,-)-from products.experiments.backend.health.split_changes import (- same_assignment,- split_change_from_activity,- split_variant_keys,)+from products.experiments.backend.health.split_changes import split_change_from_activityfrom products.experiments.backend.hogql_queries.exposure_query_logic import (aggregates_by_group,build_exposure_event_conditions,@@ -95,6 +78,20 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (resolve_default_exposure_event,)from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.facade.edits import (+ BucketingChange,+ BucketingSetting,+ ConditionsChange,+ Split,+ SplitChange,+ bucketing_changes_from_activity,+ changes_that_apply,+ conditions_follow_flag_aggregation,+ parse_release_conditions,+ parse_variants,+ same_assignment,+ split_variant_keys,+)MAX_EXPOSURE_QUERIES = 20# Each override window costs a cache read, and a query when the answer is not cached. A window past this staysdiff --git a/products/experiments/backend/health/inputs_payload.py b/products/experiments/backend/health/inputs_payload.pyindex 36bba862a499..7b31a6bd6b45 100644--- a/products/experiments/backend/health/inputs_payload.py+++ b/products/experiments/backend/health/inputs_payload.py@@ -12,20 +12,22 @@ from products.experiments.backend.health.condition_set_traffic import (needs_condition_set_traffic,)from products.experiments.backend.health.context import (- BucketingChange,- BucketingSetting,- ConditionsChange,ConditionSetTraffic,FlagChange,FlagHistory,FlagHistoryNotChecked,FlagState,+)+from products.experiments.backend.health.exposure_inputs import ExposureInputs+from products.experiments.backend.health.loader import HealthInputs+from products.feature_flags.backend.facade.edits import (+ BucketingChange,+ BucketingSetting,+ ConditionsChange,ReleaseCondition,Split,SplitChange,)-from products.experiments.backend.health.exposure_inputs import ExposureInputs-from products.experiments.backend.health.loader import HealthInputsdef _health_inputs_split(split: Split) -> list[dict[str, Any]]:diff --git a/products/experiments/backend/health/pinned_share.py b/products/experiments/backend/health/pinned_share.pyindex 7ced02c0bb7a..11eb85832d68 100644--- a/products/experiments/backend/health/pinned_share.py+++ b/products/experiments/backend/health/pinned_share.py@@ -11,8 +11,9 @@ from enum import StrEnumfrom posthog.dataclasses import frozenfrom products.experiments.backend.facade.contracts import ExperimentHealthFindingSeverity-from products.experiments.backend.health.context import ConditionSetTraffic, ReachableCondition, Split+from products.experiments.backend.health.context import ConditionSetTraffic, ReachableConditionfrom products.experiments.backend.health.split_changes import format_change_time+from products.feature_flags.backend.facade.edits import Split# A finding is graded by 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 adiff --git a/products/experiments/backend/health/split_changes.py b/products/experiments/backend/health/split_changes.pyindex 8c5856c67e01..ed0aa957e0e1 100644--- a/products/experiments/backend/health/split_changes.py+++ b/products/experiments/backend/health/split_changes.py@@ -1,11 +1,9 @@"""Changes of a flag's variant split, read from the flag's activity log. Pure functions, no I/O.-The flag service draws a variant from a hash, and each variant is a slot of the split in stored order-(`select_variant` in `rust/feature-flags/src/flags/v1_bucketing.rs`). A changed split moves the slot boundaries,-so people whose hash lies between an old and a new boundary get another variant. A rollout change, or a-release-condition change without a variant override, moves people into or out of the flag, never to another-variant, so only the split counts here.+A rollout change, or a release-condition change without a variant override, moves people into or out of the flag,+never to another variant, so only the split counts here. The flags facade (`facade/edits.py`) owns how a split+assigns variants."""from collections import Counter@@ -16,7 +14,17 @@ from zoneinfo import ZoneInfofrom posthog.dataclasses import frozen-from products.experiments.backend.health.context import Split, SplitChange, parse_variants+from products.feature_flags.backend.facade.edits import (+ Split,+ SplitChange,+ added_variant_keys,+ parse_variants,+ removed_variant_keys,+ rolled_out_variant_key,+ same_assignment,+ served_slots,+ zeroed_variant_keys,+)class SplitChangeShape(StrEnum):@@ -96,45 +104,6 @@ def net_effect(changes: Sequence[SplitChange]) -> SplitNetEffect | None:)-def served_slots(split: Split) -> Split:- # The flag service walks the cumulative percentages in order, so a variant at 0% has no range and serves- # nobody. A percentage it can't read counts as served.- return tuple(variant for variant in split if variant.rollout_percentage != 0)---def same_assignment(before: Split, after: Split) -> bool:- """Whether both splits give every person the same variant."""- return served_slots(before) == served_slots(after)---def rolled_out_variant_key(split: Split) -> str | None:- # A holdout is drawn before the split with a hash of its own, so one variant at 100% is a rollout also- # when the flag has a holdout.- full = [variant for variant in split if variant.rollout_percentage == 100]- return full[0].key if len(full) == 1 else None---def removed_variant_keys(before: Split, after: Split) -> list[str]:- return _keys_missing_from(after, split=served_slots(before))---def added_variant_keys(before: Split, after: Split) -> list[str]:- return _keys_missing_from(before, split=served_slots(after))---def zeroed_variant_keys(before: Split, after: Split) -> list[str]:- served_before = {variant.key for variant in served_slots(before)}- return [- variant.key- for variant in after- if variant.key and variant.rollout_percentage == 0 and variant.key in served_before- ]---def split_variant_keys(split: Split) -> tuple[str, ...]:- return tuple(variant.key for variant in split if variant.key)--def describe_split(split: Split) -> str:"""The split as the evidence and the wording show it, for example "control 50% / test 50%"."""if not split:@@ -151,8 +120,3 @@ def format_change_time(value: datetime, team_timezone: str) -> str:# The format of the alert messages (posthog/tasks/alerts/utils.py). The time matters, because a start# date moved to the change must not keep the hours before it.return value.astimezone(ZoneInfo(team_timezone)).strftime("%B %-d, %Y at %-I:%M %p %Z")---def _keys_missing_from(other: Split, *, split: Split) -> list[str]:- other_keys = {variant.key for variant in other}- return [variant.key for variant in split if variant.key and variant.key not in other_keys]diff --git a/products/experiments/backend/health/test/factories.py b/products/experiments/backend/health/test/factories.pyindex 8e32e3ae975a..3a18f9ce2cc1 100644--- a/products/experiments/backend/health/test/factories.py+++ b/products/experiments/backend/health/test/factories.py@@ -5,15 +5,14 @@ from typing import TypedDictfrom products.experiments.backend.facade.contracts import ExperimentHealthFlagChangeKindfrom products.experiments.backend.health.context import (ChangeWindow,- ConditionsChange,ExposureEvents,FlagChange,FlagHistory,FlagHistoryNotChecked,FlagHistoryNotCheckedReason,HealthContext,- ReleaseCondition,)+from products.feature_flags.backend.facade.edits import ConditionsChange, ReleaseCondition# Tests set what their check reads with `dataclasses.replace`, so a new field of the context changes only this file.RUNNING_CONTEXT = HealthContext(diff --git a/products/experiments/backend/health/test/test_bucketing_changed.py b/products/experiments/backend/health/test/test_bucketing_changed.pyindex ed4e20c12d87..e654f49cdcd5 100644--- a/products/experiments/backend/health/test/test_bucketing_changed.py+++ b/products/experiments/backend/health/test/test_bucketing_changed.py@@ -13,14 +13,9 @@ from products.experiments.backend.facade.contracts import (ExperimentHealthFlagChangeKind,)from products.experiments.backend.health.checks.bucketing_changed import bucketing_changed_mid_run-from products.experiments.backend.health.context import (- BucketingChange,- BucketingSetting,- FlagHistoryNotCheckedReason,- HealthContext,- parse_flag_state,-)+from products.experiments.backend.health.context import FlagHistoryNotCheckedReason, HealthContext, parse_flag_statefrom products.experiments.backend.health.test.factories import RUNNING_CONTEXT, flag_history+from products.feature_flags.backend.facade.edits import BucketingChange, BucketingSettingLAUNCHED_AT = datetime(2026, 9, 12, 10, 0, tzinfo=UTC)FIRST_CHANGE_AT = datetime(2026, 9, 12, 13, 4, tzinfo=UTC)diff --git a/products/experiments/backend/health/test/test_bucketing_changes.py b/products/experiments/backend/health/test/test_bucketing_changes.pyindex 0ebcc85eb2d4..9e60556ef793 100644--- a/products/experiments/backend/health/test/test_bucketing_changes.py+++ b/products/experiments/backend/health/test/test_bucketing_changes.py@@ -4,17 +4,10 @@ from unittest import TestCasefrom parameterized import parameterized-from products.experiments.backend.health.bucketing_changes import (- BucketingChangeShape,- bucketing_changes_from_activity,- bucketing_net_effect,- changes_that_apply,- conditions_follow_flag_aggregation,-)-from products.experiments.backend.health.context import BucketingChange, BucketingSetting+from products.experiments.backend.health.bucketing_changes import BucketingChangeShape, bucketing_net_effect+from products.feature_flags.backend.facade.edits import BucketingChange, BucketingSettingCHANGED_AT = datetime(2026, 9, 12, 13, 4, tzinfo=UTC)-FLAG_ID = 42KEY = BucketingSetting.KEYAGGREGATION = BucketingSetting.AGGREGATIONIDENTIFIER = BucketingSetting.BUCKETING_IDENTIFIER@@ -31,44 +24,6 @@ def _change(setting: BucketingSetting, before: Value, after: Value, *, minutes:class TestBucketingChanges(TestCase):- @parameterized.expand(- [- ("key_renamed", {KEY: "old"}, {KEY: "new"}, [(KEY, "old", "new")]),- ("key_tombstoned_on_delete", {KEY: "old"}, {KEY: f"old:deleted:{FLAG_ID}"}, []),- ("key_restored_under_a_new_name", {KEY: f"old:deleted:{FLAG_ID}"}, {KEY: "old-2"}, [(KEY, "old", "old-2")]),- (- "identifier_to_device",- {IDENTIFIER: "distinct_id"},- {IDENTIFIER: "device_id"},- [(IDENTIFIER, "distinct_id", "device_id")],- ),- ("identifier_default_written", {IDENTIFIER: None}, {IDENTIFIER: "distinct_id"}, []),- ("continuity_on", {CONTINUITY: False}, {CONTINUITY: True}, [(CONTINUITY, False, True)]),- ("continuity_default_written", {CONTINUITY: None}, {CONTINUITY: False}, []),- ("aggregation_to_group", {AGGREGATION: None}, {AGGREGATION: 0}, [(AGGREGATION, None, 0)]),- ("aggregation_boolean_is_unreadable", {AGGREGATION: None}, {AGGREGATION: False}, []),- ("row_without_these_settings", {}, {}, []),- (- "one_save_changes_two",- {KEY: "old", CONTINUITY: True},- {KEY: "new", CONTINUITY: False},- [(KEY, "old", "new"), (CONTINUITY, True, False)],- ),- ]- )- def test_bucketing_changes_from_activity(- self,- _name: str,- before: dict[BucketingSetting, object],- after: dict[BucketingSetting, object],- expected: list[tuple[BucketingSetting, object, object]],- ) -> None:- changes = bucketing_changes_from_activity(- changed_at=CHANGED_AT, feature_flag_id=FLAG_ID, before=before, after=after- )-- self.assertEqual([(change.setting, change.before, change.after) for change in changes], expected)-@parameterized.expand([(@@ -122,117 +77,3 @@ class TestBucketingChanges(TestCase):self.assertEqual(effect.shape, expected_shape)self.assertEqual([change.setting for change in effect.net_changes], expected_net_settings)self.assertEqual(effect.change_count, expected_change_count)-- @parameterized.expand(- [- (- "identifier_on_a_user_flag",- [_change(IDENTIFIER, "distinct_id", "device_id")],- None,- None,- [_change(IDENTIFIER, "distinct_id", "device_id")],- ),- ("identifier_on_a_group_flag", [_change(IDENTIFIER, "distinct_id", "device_id")], 0, None, []),- (- "identifier_on_a_group_flag_with_a_person_condition",- [_change(IDENTIFIER, "distinct_id", "device_id")],- 0,- "device_id",- [_change(IDENTIFIER, "distinct_id", "device_id")],- False,- ),- (- "continuity_under_user_id",- [_change(CONTINUITY, False, True)],- None,- None,- [_change(CONTINUITY, False, True)],- ),- ("continuity_under_device_id", [_change(CONTINUITY, True, False)], None, "device_id", []),- ("continuity_on_a_group_flag", [_change(CONTINUITY, False, True)], 0, None, []),- # The state right after each save decides, not the state today.- (- "identifier_before_a_switch_to_groups",- [_change(IDENTIFIER, "distinct_id", "device_id"), _change(AGGREGATION, None, 0, minutes=5)],- 0,- "device_id",- [_change(IDENTIFIER, "distinct_id", "device_id"), _change(AGGREGATION, None, 0, minutes=5)],- ),- (- "continuity_in_the_save_that_switches_to_device_id",- [_change(IDENTIFIER, "distinct_id", "device_id"), _change(CONTINUITY, True, False)],- None,- "device_id",- [_change(IDENTIFIER, "distinct_id", "device_id")],- ),- (- "identifier_set_back_while_grouped",- [- _change(IDENTIFIER, "distinct_id", "device_id"),- _change(AGGREGATION, None, 0, minutes=5),- _change(IDENTIFIER, "device_id", "distinct_id", minutes=10),- _change(AGGREGATION, 0, None, minutes=15),- ],- None,- "distinct_id",- [- _change(IDENTIFIER, "distinct_id", "device_id"),- _change(AGGREGATION, None, 0, minutes=5),- _change(AGGREGATION, 0, None, minutes=15),- _change(IDENTIFIER, "device_id", "distinct_id", minutes=15),- ],- ),- (- "identifier_changed_while_grouped",- [- _change(AGGREGATION, None, 0),- _change(IDENTIFIER, "distinct_id", "device_id", minutes=5),- _change(AGGREGATION, 0, None, minutes=10),- ],- None,- "device_id",- [- _change(AGGREGATION, None, 0),- _change(AGGREGATION, 0, None, minutes=10),- _change(IDENTIFIER, "distinct_id", "device_id", minutes=10),- ],- ),- ("key_on_a_group_flag", [_change(KEY, "old", "new")], 0, None, [_change(KEY, "old", "new")]),- ]- )- def test_changes_that_apply(- self,- _name: str,- changes: list[BucketingChange],- aggregation: int | None,- bucketing_identifier: str | None,- expected: list[BucketingChange],- trust_flag_aggregation: bool = True,- ) -> None:- applied = changes_that_apply(- changes,- feature_flag_id=FLAG_ID,- aggregation=aggregation,- bucketing_identifier=bucketing_identifier,- trust_flag_aggregation=trust_flag_aggregation,- )-- self.assertEqual(list(applied), expected)-- @parameterized.expand(- [- ("user_flag_with_a_group_condition", None, [{"aggregation_group_type_index": 0}], True),- ("group_flag", 0, [{"aggregation_group_type_index": 0}, {"aggregation_group_type_index": 0}], True),- ("group_flag_with_a_condition_from_before_per_condition_aggregation", 0, [{}], True),- (- "group_flag_with_a_person_condition",- 0,- [{"aggregation_group_type_index": 0}, {"aggregation_group_type_index": None}],- False,- ),- ]- )- def test_conditions_follow_flag_aggregation(- self, _name: str, aggregation: int | None, conditions: list[dict[str, int | None]], expected: bool- ) -> None:- self.assertEqual(conditions_follow_flag_aggregation(aggregation, conditions), expected)diff --git a/products/experiments/backend/health/test/test_condition_changes.py b/products/experiments/backend/health/test/test_condition_changes.pyindex 6cfe0bdb5c7a..6c17e541a5dd 100644--- a/products/experiments/backend/health/test/test_condition_changes.py+++ b/products/experiments/backend/health/test/test_condition_changes.py@@ -10,7 +10,7 @@ from products.experiments.backend.health.condition_changes import (conditions_change_from_activity,conditions_net_effect,)-from products.experiments.backend.health.context import ConditionsChange+from products.feature_flags.backend.facade.edits import ConditionsChangeCHANGED_AT = datetime(2026, 9, 12, 13, 4, tzinfo=UTC)PRO = {"key": "plan", "value": ["pro"], "operator": "exact", "type": "person"}diff --git a/products/experiments/backend/health/test/test_conditions_changed.py b/products/experiments/backend/health/test/test_conditions_changed.pyindex f51a1a3e2dfd..82a9f0ea1db5 100644--- a/products/experiments/backend/health/test/test_conditions_changed.py+++ b/products/experiments/backend/health/test/test_conditions_changed.py@@ -12,16 +12,15 @@ from products.experiments.backend.facade.contracts import (ExperimentHealthFlagChangeKind,)from products.experiments.backend.health.checks.conditions_changed import release_conditions_changed_mid_run-from products.experiments.backend.health.condition_changes import parse_release_conditionsfrom products.experiments.backend.health.context import (ChangeWindow,- ConditionsChange,ConditionSetTraffic,FlagHistoryNotCheckedReason,HealthContext,parse_flag_state,)from products.experiments.backend.health.test.factories import RUNNING_CONTEXT, flag_history+from products.feature_flags.backend.facade.edits import ConditionsChange, parse_release_conditionsLAUNCHED_AT = datetime(2026, 9, 12, 10, 0, tzinfo=UTC)FIRST_CHANGE_AT = datetime(2026, 9, 12, 13, 4, tzinfo=UTC)diff --git a/products/experiments/backend/health/test/test_exposure_gate.py b/products/experiments/backend/health/test/test_exposure_gate.pyindex dccc38e0fd31..e889231b13f5 100644--- a/products/experiments/backend/health/test/test_exposure_gate.py+++ b/products/experiments/backend/health/test/test_exposure_gate.py@@ -20,14 +20,10 @@ from posthog.test.persons import create_personfrom products.experiments.backend.facade.contracts import ExperimentHealthFlagChangeKind, ExperimentHealthReaderAccessfrom products.experiments.backend.health.context import (MIN_EXPOSED_UNITS_TO_WARN,- BucketingChange,- BucketingSetting,ChangeWindow,- ConditionsChange,FlagHistory,FlagHistoryNotChecked,FlagHistoryNotCheckedReason,- SplitChange,)from products.experiments.backend.health.exposure_gate import (MAX_EXPOSURE_QUERIES,@@ -38,6 +34,7 @@ from products.experiments.backend.health.exposure_gate import ()from products.experiments.backend.hogql_queries.exposure_query_logic import DEFAULT_EXPOSURE_EVENTfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.facade.edits import BucketingChange, BucketingSetting, ConditionsChange, SplitChangefrom products.feature_flags.backend.models.feature_flag import FeatureFlagFLAG_KEY = "split-gate"diff --git a/products/experiments/backend/health/test/test_forced_variant.py b/products/experiments/backend/health/test/test_forced_variant.pyindex 3b94b59b8db4..972857ca5271 100644--- a/products/experiments/backend/health/test/test_forced_variant.py+++ b/products/experiments/backend/health/test/test_forced_variant.py@@ -8,10 +8,8 @@ from parameterized import parameterizedfrom products.experiments.backend.facade.contracts import ExperimentHealthFindingSeverityfrom products.experiments.backend.health.checks.forced_variant import forced_variant_release_condition-from products.experiments.backend.health.condition_changes import parse_release_conditionsfrom products.experiments.backend.health.condition_set_traffic import grades_by_pinned_sharefrom products.experiments.backend.health.context import (- ConditionsChange,ConditionSetTraffic,FlagHistory,FlagHistoryNotChecked,@@ -26,6 +24,7 @@ from products.experiments.backend.health.test.factories import (Status,flag_history,)+from products.feature_flags.backend.facade.edits import ConditionsChange, parse_release_conditionsEVEN_SPLIT = [{"key": "control", "rollout_percentage": 50}, {"key": "test", "rollout_percentage": 50}]SHIPPED_SPLIT = [{"key": "control", "rollout_percentage": 0}, {"key": "test", "rollout_percentage": 100}]diff --git a/products/experiments/backend/health/test/test_registry.py b/products/experiments/backend/health/test/test_registry.pyindex 022ed531a49e..52b61655e243 100644--- a/products/experiments/backend/health/test/test_registry.py+++ b/products/experiments/backend/health/test/test_registry.py@@ -21,7 +21,6 @@ from products.experiments.backend.health.context import (FlagHistoryNotCheckedReason,FlagKeyFilter,FlagState,- FlagVariant,HealthContext,MetricEvents,)@@ -32,6 +31,7 @@ from products.experiments.backend.health.registry import (evaluate,)from products.experiments.backend.health.test.factories import DRAFT, RUNNING_CONTEXT, flag_history+from products.feature_flags.backend.facade.edits import FlagVariantUNEVEN_SPLIT_TOTALS = ExposureTotals(total_exposures={"control": 800, "test": 200, "$multiple": 20},diff --git a/products/experiments/backend/health/test/test_split_changed.py b/products/experiments/backend/health/test/test_split_changed.pyindex 9c2ac56f7eeb..cb62d3bf1e0b 100644--- a/products/experiments/backend/health/test/test_split_changed.py+++ b/products/experiments/backend/health/test/test_split_changed.py@@ -16,14 +16,9 @@ from products.experiments.backend.facade.contracts import (from products.experiments.backend.health.checks.flag_change_findings import flag_history_not_readablefrom products.experiments.backend.health.checks.flag_state import flag_statefrom products.experiments.backend.health.checks.split_changed import split_changed_mid_run-from products.experiments.backend.health.context import (- FlagHistoryNotCheckedReason,- HealthContext,- SplitChange,- parse_flag_state,- parse_variants,-)+from products.experiments.backend.health.context import FlagHistoryNotCheckedReason, HealthContext, parse_flag_statefrom products.experiments.backend.health.test.factories import ENDED, RUNNING, RUNNING_CONTEXT, Status, flag_history+from products.feature_flags.backend.facade.edits import SplitChange, parse_variantsLAUNCHED_AT = datetime(2026, 9, 12, 10, 0, tzinfo=UTC)FIRST_CHANGE_AT = datetime(2026, 9, 12, 13, 4, tzinfo=UTC)diff --git a/products/experiments/backend/health/test/test_split_changes.py b/products/experiments/backend/health/test/test_split_changes.pyindex c6e8d8201ed2..56ff8db6aede 100644--- a/products/experiments/backend/health/test/test_split_changes.py+++ b/products/experiments/backend/health/test/test_split_changes.py@@ -5,13 +5,13 @@ from unittest import TestCasefrom parameterized import parameterized-from products.experiments.backend.health.context import SplitChangefrom products.experiments.backend.health.split_changes import (SplitChangeShape,net_effect,split_change_from_activity,split_shape,)+from products.feature_flags.backend.facade.edits import SplitChangeCHANGED_AT = datetime(2026, 9, 12, 13, 4, tzinfo=UTC)diff --git a/products/feature_flags/backend/facade/edits.py b/products/feature_flags/backend/facade/edits.pynew file mode 100644index 000000000000..e4c803b6c75c--- /dev/null+++ b/products/feature_flags/backend/facade/edits.py@@ -0,0 +1,454 @@+"""What an edit of a feature flag does to who gets which value. Pure functions, no I/O.++Callers read the before and after values of a flag save, usually from the flag's activity log, and pass them+here. These functions own the flag service's rules for the variant split, the release conditions, and the+settings that decide a person's variant draw, so consumers don't derive them again.++Deliberately free of Django/DRF imports (same reason as ``facade.filters``): consumer model modules import+these at module level.+"""++import json+from collections import deque+from collections.abc import Callable, Collection, Hashable, Mapping, Sequence+from datetime import datetime+from enum import StrEnum+from itertools import groupby++from posthog.dataclasses import frozen++from products.feature_flags.backend.facade.filters import condition_aggregation, pinned_variant++# Variants and the split+#+# The flag service draws a variant from a hash, and each variant is a slot of the split in stored order+# (`select_variant` in `rust/feature-flags/src/flags/v1_bucketing.rs`). A changed split moves the slot boundaries,+# so people whose hash lies between an old and a new boundary get another variant. A rollout change, or a+# release-condition change without a variant override, moves people into or out of the flag, never to another+# variant.+++@frozen+class FlagVariant:+ key: str | None+ rollout_percentage: float | None+++Split = tuple[FlagVariant, ...]+++@frozen+class SplitChange:+ changed_at: datetime+ before: Split+ after: Split+++def parse_variants(variants: object) -> Split:+ return tuple(_flag_variant(variant) for variant in variants) if isinstance(variants, list) else ()+++def parse_percentage(value: object) -> float | None:+ # Only a JSON number is a percentage. A string or a boolean is not, and Python's `False == 0` would let a+ # boolean through.+ if isinstance(value, bool) or not isinstance(value, int | float):+ return None+ return float(value)+++def served_slots(split: Split) -> Split:+ # The flag service walks the cumulative percentages in order, so a variant at 0% has no range and serves+ # nobody. A percentage it can't read counts as served.+ return tuple(variant for variant in split if variant.rollout_percentage != 0)+++def same_assignment(before: Split, after: Split) -> bool:+ """Whether both splits give every person the same variant."""+ return served_slots(before) == served_slots(after)+++def rolled_out_variant_key(split: Split) -> str | None:+ # A holdout is drawn before the split with a hash of its own, so one variant at 100% is a rollout also+ # when the flag has a holdout.+ full = [variant for variant in split if variant.rollout_percentage == 100]+ return full[0].key if len(full) == 1 else None+++def removed_variant_keys(before: Split, after: Split) -> list[str]:+ return _keys_missing_from(after, split=served_slots(before))+++def added_variant_keys(before: Split, after: Split) -> list[str]:+ return _keys_missing_from(before, split=served_slots(after))+++def zeroed_variant_keys(before: Split, after: Split) -> list[str]:+ served_before = {variant.key for variant in served_slots(before)}+ return [+ variant.key+ for variant in after+ if variant.key and variant.rollout_percentage == 0 and variant.key in served_before+ ]+++def split_variant_keys(split: Split) -> tuple[str, ...]:+ return tuple(variant.key for variant in split if variant.key)+++def _flag_variant(variant: object) -> FlagVariant:+ if not isinstance(variant, dict):+ return FlagVariant(key=None, rollout_percentage=None)+ key = variant.get("key")+ return FlagVariant(+ key=key if isinstance(key, str) else None,+ rollout_percentage=parse_percentage(variant.get("rollout_percentage")),+ )+++def _keys_missing_from(other: Split, *, split: Split) -> list[str]:+ other_keys = {variant.key for variant in other}+ return [variant.key for variant in split if variant.key and variant.key not in other_keys]+++# Release conditions+#+# A condition whose criteria change, or a condition that is added or removed, moves people into or out of the flag,+# never to another variant (`get_match` in rust/feature-flags/src/flags/flag_matching.rs). A variant override does+# move people: everyone a condition with an override matches gets that variant instead of the one from the hash.+# The flag service evaluates the conditions in order, so the order moves people who match two conditions that serve+# different variants.+++@frozen+class ReleaseCondition:+ # The group type and property filters of the condition, as a signature that is equal for two conditions+ # that match the same people under the flag-level aggregation of their save. The rollout is not part of it.+ criteria: str+ # The group type index that the condition matches, None for persons, and the keys of its property filters.+ # The flag page's history pairs two conditions that share them as one condition edited.+ aggregation: int | None+ property_keys: frozenset[str]+ rollout: float+ variant: str | None+++ReleaseConditions = tuple[ReleaseCondition, ...]+++@frozen+class ConditionsChange:+ changed_at: datetime+ before: ReleaseConditions+ after: ReleaseConditions+++_MAX_LOOK_ALIKES = 100+_FOLLOWS_FLAG_AGGREGATION = "flag"+++def parse_release_conditions(+ groups: object, *, flag_aggregation: object = None, variant_keys: Collection[str]+) -> ReleaseConditions:+ """`variant_keys` are the variants of the flag in the same version, because the flag service ignores an+ override that names no variant of the flag."""+ aggregation = _group_type_index(flag_aggregation)+ return tuple(_condition(group, aggregation, variant_keys) for group in groups) if isinstance(groups, list) else ()+++def pair_conditions(before: ReleaseConditions, after: ReleaseConditions) -> dict[int, int]:+ """+ The condition that each condition after a change was before it, as indexes from `after` to `before`. A+ condition without a pair was added or removed. The pairing is the one of the flag page's history+ (`diffReleaseConditionSets` in releaseConditionsDiff.ts): an unchanged condition first, then one with the same+ criteria, then a look-alike at the same position, then the only look-alike left.+ """+ pairs: dict[int, int] = {}+ paired: set[int] = set()++ def pair(after_index: int, before_index: int) -> None:+ pairs[after_index] = before_index+ paired.add(before_index)++ def pair_first_with_same(key: Callable[[ReleaseCondition], Hashable]) -> None:+ waiting: dict[Hashable, deque[int]] = {}+ for index, old in enumerate(before):+ if index not in paired:+ waiting.setdefault(key(old), deque()).append(index)+ for after_index, condition in enumerate(after):+ candidates = waiting.get(key(condition))+ if after_index not in pairs and candidates:+ pair(after_index, candidates.popleft())++ pair_first_with_same(lambda condition: condition)+ pair_first_with_same(lambda condition: condition.criteria)+ unpaired_after = [index for index in range(len(after)) if index not in pairs]+ unpaired_before = [index for index in range(len(before)) if index not in paired]+ # Look-alikes are compared each with each. A save that edits more conditions than this pairs no more of them,+ # so they count as removed and added, which bounds the work for a flag with very many conditions.+ if len(unpaired_after) > _MAX_LOOK_ALIKES or len(unpaired_before) > _MAX_LOOK_ALIKES:+ return pairs+ for after_index in unpaired_after:+ if (+ after_index < len(before)+ and after_index not in paired+ and _looks_alike(before[after_index], after[after_index])+ ):+ pair(after_index, after_index)+ # A condition that was edited and moved in one save has no partner at its position. It pairs with the one+ # condition left that it looks like. With several, no pair is safe, so they count as removed and added.+ for after_index in unpaired_after:+ if after_index in pairs:+ continue+ candidates = [+ index+ for index in unpaired_before+ if index not in paired and _looks_alike(before[index], after[after_index])+ ]+ if len(candidates) == 1:+ pair(after_index, candidates[0])+ return pairs+++def moves_people(before: ReleaseCondition | None, after: ReleaseCondition | None) -> bool:+ """Whether a condition's change of override moves the people it matches to another variant."""+ # A condition at 0% rollout serves nobody, so its override moves nobody.+ return _variant(before) != _variant(after) and any(+ condition is not None and condition.rollout > 0 for condition in (before, after)+ )+++def order_moves_people(before: ReleaseConditions, after: ReleaseConditions, pairs: Mapping[int, int]) -> bool:+ """Whether the new order gives a person who matches two conditions another variant. `pairs` are the pairs+ of `pair_conditions`."""+ # A person who matches two conditions gets the variant of the first one, the override or the hash's. Walking+ # the conditions in their new order, a condition moved ahead of one with another variant when that one sat+ # later before the change. Keeping the latest position and the latest of any other variant finds it in one pass.+ latest: tuple[int, str | None] | None = None+ latest_of_other_variant = -1+ for after_index, before_index in sorted(pairs.items()):+ if before[before_index].rollout <= 0 or after[after_index].rollout <= 0:+ continue+ variant = after[after_index].variant+ if latest is not None:+ latest_position, latest_variant = latest+ if (latest_position if latest_variant != variant else latest_of_other_variant) > before_index:+ return True+ if variant == latest_variant:+ latest = (max(latest_position, before_index), variant)+ elif before_index > latest_position:+ latest_of_other_variant = latest_position+ latest = (before_index, variant)+ else:+ latest_of_other_variant = max(latest_of_other_variant, before_index)+ else:+ latest = (before_index, variant)+ return False+++def _variant(condition: ReleaseCondition | None) -> str | None:+ return condition.variant if condition is not None else None+++def _looks_alike(old: ReleaseCondition, new: ReleaseCondition) -> bool:+ # Two conditions look alike when they match the same kind of thing: the same group type, and a shared property+ # key or no properties on either. Otherwise an unrelated new condition would read as an edit.+ if old.aggregation != new.aggregation:+ return False+ if not old.property_keys and not new.property_keys:+ return True+ return bool(old.property_keys & new.property_keys)+++def _condition(group: object, flag_aggregation: int | None, variant_keys: Collection[str]) -> ReleaseCondition:+ if not isinstance(group, dict):+ return ReleaseCondition(+ criteria=json.dumps(group, sort_keys=True, default=str),+ aggregation=None,+ property_keys=frozenset(),+ rollout=100,+ variant=None,+ )+ properties = group.get("properties")+ rollout = group.get("rollout_percentage")+ aggregation = condition_aggregation(group, flag_aggregation)+ return ReleaseCondition(+ criteria=json.dumps(+ [+ # A change of the flag-level aggregation is a bucketing change, so a condition that follows it keeps+ # its criteria.+ _FOLLOWS_FLAG_AGGREGATION if aggregation == flag_aggregation else aggregation,+ # The filters of a condition all have to match, so their order does not matter.+ sorted(_property_signature(prop) for prop in properties) if isinstance(properties, list) else None,+ ],+ sort_keys=True,+ default=str,+ ),+ aggregation=_group_type_index(aggregation),+ property_keys=frozenset(_property_key(prop) for prop in properties)+ if isinstance(properties, list)+ else frozenset(),+ # The flag service reads a missing rollout as 100%.+ rollout=rollout if isinstance(rollout, int | float) and not isinstance(rollout, bool) else 100,+ variant=pinned_variant(group, variant_keys),+ )+++def _property_signature(prop: object) -> str:+ # The fields that decide a match, as the flag page's history compares them (releaseConditionsDiff.ts).+ if not isinstance(prop, dict):+ return json.dumps(prop, sort_keys=True, default=str)+ return json.dumps(+ [prop.get(field) for field in ("type", "key", "operator", "value", "group_type_index")],+ sort_keys=True,+ default=str,+ )+++def _property_key(prop: object) -> str:+ if not isinstance(prop, dict):+ return json.dumps(prop, sort_keys=True, default=str)+ return f"{prop.get('type') or ''}:{prop.get('key') or ''}"+++# Bucketing+#+# The flag service hashes the flag key with an identifier: the group key for a flag that aggregates by a group type,+# otherwise the device ID or the distinct ID, as `bucketing_identifier` says, and with experience continuity the+# person's stored anonymous ID (`hashed_identifier` in rust/feature-flags/src/flags/flag_matching.rs). A change of any+# of them gives the people it touches a new draw, so they can get another variant.+++class BucketingSetting(StrEnum):+ # The flag settings besides the split that are inputs of the variant draw. The functions below return changes+ # in this order, and callers rely on it.+ KEY = "key"+ AGGREGATION = "aggregation"+ BUCKETING_IDENTIFIER = "bucketing_identifier"+ EXPERIENCE_CONTINUITY = "experience_continuity"+++@frozen+class BucketingChange:+ changed_at: datetime+ setting: BucketingSetting+ # The key as a string, the aggregation as a group type index or None for persons, the identifier as+ # "distinct_id" or "device_id", the continuity as a bool.+ before: str | int | bool | None+ after: str | int | bool | None+++def bucketing_changes_from_activity(+ *,+ changed_at: datetime,+ feature_flag_id: int,+ before: Mapping[BucketingSetting, object],+ after: Mapping[BucketingSetting, object],+) -> list[BucketingChange]:+ """The bucketing changes in one activity log row of the flag. A setting the row does not change is absent."""+ changes = []+ for setting in BucketingSetting:+ value_before = _normalized(setting, before.get(setting), feature_flag_id)+ value_after = _normalized(setting, after.get(setting), feature_flag_id)+ if value_before != value_after:+ changes.append(+ BucketingChange(changed_at=changed_at, setting=setting, before=value_before, after=value_after)+ )+ return changes+++def conditions_follow_flag_aggregation(aggregation: object, conditions: Sequence[object]) -> bool:+ """+ Whether no release condition aggregates by person while the flag-level aggregation names a group type.+ `changes_that_apply` relies on this, because it reads only the flag-level aggregation of each save. The flag+ serializer keeps it true: it sets the flag-level aggregation to null when the conditions mix aggregations.+ """+ flag_aggregation = _group_type_index(aggregation)+ return flag_aggregation is None or all(+ condition_aggregation(condition, flag_aggregation) is not None+ for condition in conditions+ if isinstance(condition, dict)+ )+++def changes_that_apply(+ changes: Sequence[BucketingChange],+ *,+ feature_flag_id: int,+ aggregation: object,+ bucketing_identifier: object,+ trust_flag_aggregation: bool,+) -> tuple[BucketingChange, ...]:+ """+ The changes as the flag service reads them, save by save. It hashes the group key for a flag that aggregates by+ a group type, so it does not read the bucketing identifier and persistence there. It hashes the device ID before+ it reads persistence, so it does not read persistence under device ID bucketing either.++ A setting that changes while the flag service does not read it moves nobody at that save. The new value takes+ effect at the save after which the flag service reads the setting again, so the change counts there, from the+ value that the flag service read last.++ `aggregation` and `bucketing_identifier` are the flag's current values. When `trust_flag_aggregation` is false,+ a release condition can aggregate by person under any flag-level aggregation, so the flag-level aggregation does+ not stop the flag service from reading the identifier.+ """+ state: dict[BucketingSetting, str | int | bool | None] = {+ BucketingSetting.AGGREGATION: _normalized(BucketingSetting.AGGREGATION, aggregation, feature_flag_id),+ BucketingSetting.BUCKETING_IDENTIFIER: _normalized(+ BucketingSetting.BUCKETING_IDENTIFIER, bucketing_identifier, feature_flag_id+ ),+ }+ # Each setting holds the `before` of its first change until that change, and its current value without one.+ for change in reversed(changes):+ state[change.setting] = change.before++ def reads(setting: BucketingSetting) -> bool:+ by_person = state[BucketingSetting.AGGREGATION] is None or not trust_flag_aggregation+ match setting:+ case BucketingSetting.BUCKETING_IDENTIFIER:+ return by_person+ case BucketingSetting.EXPERIENCE_CONTINUITY:+ return by_person and state[BucketingSetting.BUCKETING_IDENTIFIER] == "distinct_id"+ case _:+ return True++ last_read = {setting: value for setting, value in state.items() if reads(setting)}+ applied = []+ for changed_at, saved in groupby(changes, key=lambda change: change.changed_at):+ for change in saved:+ state[change.setting] = change.after+ for setting in BucketingSetting:+ if setting not in state or not reads(setting):+ continue+ # A setting that the flag service never read before has no earlier value to count from. The change+ # that made the flag service read it, such as an aggregation change, counts instead.+ if setting in last_read and last_read[setting] != state[setting]:+ applied.append(+ BucketingChange(+ changed_at=changed_at, setting=setting, before=last_read[setting], after=state[setting]+ )+ )+ last_read[setting] = state[setting]+ return tuple(applied)+++def _normalized(setting: BucketingSetting, value: object, feature_flag_id: int) -> str | int | bool | None:+ # Each setting is read the way the flag service reads it, so a save that writes the default explicitly is+ # no change.+ match setting:+ case BucketingSetting.KEY:+ if not isinstance(value, str):+ return None+ # Soft-deleting a flag appends this suffix to its key (`FeatureFlag.tombstoned_key`), and restoring it+ # removes the suffix again. Neither is a new key.+ tombstone = f":deleted:{feature_flag_id}"+ return value.removesuffix(tombstone)+ case BucketingSetting.AGGREGATION:+ return _group_type_index(value)+ case BucketingSetting.BUCKETING_IDENTIFIER:+ return "device_id" if value == "device_id" else "distinct_id"+ case BucketingSetting.EXPERIENCE_CONTINUITY:+ return value is True+++def _group_type_index(value: object) -> int | None:+ return value if isinstance(value, int) and not isinstance(value, bool) else Nonediff --git a/products/feature_flags/backend/test/test_facade_edits.py b/products/feature_flags/backend/test/test_facade_edits.pynew file mode 100644index 000000000000..735e77fc5c8e--- /dev/null+++ b/products/feature_flags/backend/test/test_facade_edits.py@@ -0,0 +1,183 @@+from datetime import UTC, datetime, timedelta++from unittest import TestCase++from parameterized import parameterized++from products.feature_flags.backend.facade.edits import (+ BucketingChange,+ BucketingSetting,+ bucketing_changes_from_activity,+ changes_that_apply,+ conditions_follow_flag_aggregation,+)++CHANGED_AT = datetime(2026, 9, 12, 13, 4, tzinfo=UTC)+FLAG_ID = 42+KEY = BucketingSetting.KEY+AGGREGATION = BucketingSetting.AGGREGATION+IDENTIFIER = BucketingSetting.BUCKETING_IDENTIFIER+CONTINUITY = BucketingSetting.EXPERIENCE_CONTINUITY+++Value = str | int | bool | None+++def _change(setting: BucketingSetting, before: Value, after: Value, *, minutes: int = 0) -> BucketingChange:+ return BucketingChange(+ changed_at=CHANGED_AT + timedelta(minutes=minutes), setting=setting, before=before, after=after+ )+++class TestBucketingEdits(TestCase):+ @parameterized.expand(+ [+ ("key_renamed", {KEY: "old"}, {KEY: "new"}, [(KEY, "old", "new")]),+ ("key_tombstoned_on_delete", {KEY: "old"}, {KEY: f"old:deleted:{FLAG_ID}"}, []),+ ("key_restored_under_a_new_name", {KEY: f"old:deleted:{FLAG_ID}"}, {KEY: "old-2"}, [(KEY, "old", "old-2")]),+ (+ "identifier_to_device",+ {IDENTIFIER: "distinct_id"},+ {IDENTIFIER: "device_id"},+ [(IDENTIFIER, "distinct_id", "device_id")],+ ),+ ("identifier_default_written", {IDENTIFIER: None}, {IDENTIFIER: "distinct_id"}, []),+ ("continuity_on", {CONTINUITY: False}, {CONTINUITY: True}, [(CONTINUITY, False, True)]),+ ("continuity_default_written", {CONTINUITY: None}, {CONTINUITY: False}, []),+ ("aggregation_to_group", {AGGREGATION: None}, {AGGREGATION: 0}, [(AGGREGATION, None, 0)]),+ ("aggregation_boolean_is_unreadable", {AGGREGATION: None}, {AGGREGATION: False}, []),+ ("row_without_these_settings", {}, {}, []),+ (+ "one_save_changes_two",+ {KEY: "old", CONTINUITY: True},+ {KEY: "new", CONTINUITY: False},+ [(KEY, "old", "new"), (CONTINUITY, True, False)],+ ),+ ]+ )+ def test_bucketing_changes_from_activity(+ self,+ _name: str,+ before: dict[BucketingSetting, object],+ after: dict[BucketingSetting, object],+ expected: list[tuple[BucketingSetting, object, object]],+ ) -> None:+ changes = bucketing_changes_from_activity(+ changed_at=CHANGED_AT, feature_flag_id=FLAG_ID, before=before, after=after+ )++ self.assertEqual([(change.setting, change.before, change.after) for change in changes], expected)++ @parameterized.expand(+ [+ (+ "identifier_on_a_user_flag",+ [_change(IDENTIFIER, "distinct_id", "device_id")],+ None,+ None,+ [_change(IDENTIFIER, "distinct_id", "device_id")],+ ),+ ("identifier_on_a_group_flag", [_change(IDENTIFIER, "distinct_id", "device_id")], 0, None, []),+ (+ "identifier_on_a_group_flag_with_a_person_condition",+ [_change(IDENTIFIER, "distinct_id", "device_id")],+ 0,+ "device_id",+ [_change(IDENTIFIER, "distinct_id", "device_id")],+ False,+ ),+ (+ "continuity_under_user_id",+ [_change(CONTINUITY, False, True)],+ None,+ None,+ [_change(CONTINUITY, False, True)],+ ),+ ("continuity_under_device_id", [_change(CONTINUITY, True, False)], None, "device_id", []),+ ("continuity_on_a_group_flag", [_change(CONTINUITY, False, True)], 0, None, []),+ # The state right after each save decides, not the state today.+ (+ "identifier_before_a_switch_to_groups",+ [_change(IDENTIFIER, "distinct_id", "device_id"), _change(AGGREGATION, None, 0, minutes=5)],+ 0,+ "device_id",+ [_change(IDENTIFIER, "distinct_id", "device_id"), _change(AGGREGATION, None, 0, minutes=5)],+ ),+ (+ "continuity_in_the_save_that_switches_to_device_id",+ [_change(IDENTIFIER, "distinct_id", "device_id"), _change(CONTINUITY, True, False)],+ None,+ "device_id",+ [_change(IDENTIFIER, "distinct_id", "device_id")],+ ),+ (+ "identifier_set_back_while_grouped",+ [+ _change(IDENTIFIER, "distinct_id", "device_id"),+ _change(AGGREGATION, None, 0, minutes=5),+ _change(IDENTIFIER, "device_id", "distinct_id", minutes=10),+ _change(AGGREGATION, 0, None, minutes=15),+ ],+ None,+ "distinct_id",+ [+ _change(IDENTIFIER, "distinct_id", "device_id"),+ _change(AGGREGATION, None, 0, minutes=5),+ _change(AGGREGATION, 0, None, minutes=15),+ _change(IDENTIFIER, "device_id", "distinct_id", minutes=15),+ ],+ ),+ (+ "identifier_changed_while_grouped",+ [+ _change(AGGREGATION, None, 0),+ _change(IDENTIFIER, "distinct_id", "device_id", minutes=5),+ _change(AGGREGATION, 0, None, minutes=10),+ ],+ None,+ "device_id",+ [+ _change(AGGREGATION, None, 0),+ _change(AGGREGATION, 0, None, minutes=10),+ _change(IDENTIFIER, "distinct_id", "device_id", minutes=10),+ ],+ ),+ ("key_on_a_group_flag", [_change(KEY, "old", "new")], 0, None, [_change(KEY, "old", "new")]),+ ]+ )+ def test_changes_that_apply(+ self,+ _name: str,+ changes: list[BucketingChange],+ aggregation: int | None,+ bucketing_identifier: str | None,+ expected: list[BucketingChange],+ trust_flag_aggregation: bool = True,+ ) -> None:+ applied = changes_that_apply(+ changes,+ feature_flag_id=FLAG_ID,+ aggregation=aggregation,+ bucketing_identifier=bucketing_identifier,+ trust_flag_aggregation=trust_flag_aggregation,+ )++ self.assertEqual(list(applied), expected)++ @parameterized.expand(+ [+ ("user_flag_with_a_group_condition", None, [{"aggregation_group_type_index": 0}], True),+ ("group_flag", 0, [{"aggregation_group_type_index": 0}, {"aggregation_group_type_index": 0}], True),+ ("group_flag_with_a_condition_from_before_per_condition_aggregation", 0, [{}], True),+ (+ "group_flag_with_a_person_condition",+ 0,+ [{"aggregation_group_type_index": 0}, {"aggregation_group_type_index": None}],+ False,+ ),+ ]+ )+ def test_conditions_follow_flag_aggregation(+ self, _name: str, aggregation: int | None, conditions: list[dict[str, int | None]], expected: bool+ ) -> None:+ self.assertEqual(conditions_follow_flag_aggregation(aggregation, conditions), expected)