: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
feat(flags): bump flag version on referenced cohort condition change (#67997)
Gustavo H. Strassburgera3b0a088c32c
diff --git a/frontend/src/scenes/feature-flags/activityDescriptions.tsx b/frontend/src/scenes/feature-flags/activityDescriptions.tsxindex 3e123531001d..fa3d60056708 100644--- a/frontend/src/scenes/feature-flags/activityDescriptions.tsx+++ b/frontend/src/scenes/feature-flags/activityDescriptions.tsx@@ -432,6 +432,36 @@ export function flagActivityDescriber(logItem: ActivityLogItem, asNotification?:}if (logItem.activity == 'updated') {+ // A referenced cohort's conditions changed: the flag's own fields are untouched+ // (only its version moved), so describe the cohort change instead of a field diff.+ // job_type must stay in sync with COHORT_CONDITIONS_UPDATED_JOB_TYPE in+ // products/feature_flags/backend/flag_version_sync.py.+ if (logItem.detail.trigger?.job_type === 'cohort_conditions_updated') {+ const { cohort_id, cohort_name } = logItem.detail.trigger.payload ?? {}+ return {+ description: (+ <SentenceList+ listParts={[+ <Fragment key="cohort-conditions-updated">+ changed the conditions of linked cohort{' '}+ {cohort_id ? (+ <Link to={urls.cohort(cohort_id)}>{cohort_name || `#${cohort_id}`}</Link>+ ) : (+ <span>{cohort_name || 'unknown'}</span>+ )}+ </Fragment>,+ ]}+ prefix={getActorName(logItem)}+ suffix={+ <>+ on {asNotification && ' the flag '}+ {nameOrLinkToFlag(logItem?.item_id, logItem?.detail.name)}+ </>+ }+ />+ ),+ }+ }let changes: Description[] = []let changeSuffix: Description = (<>diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 8c51a89a81d7..0cb3cb134d09 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -155,6 +155,7 @@ post_save:products.data_warehouse.backend.models.revenue_analytics_config.createpost_save:products.event_definitions.backend.models.event_definition._invalidate_default_event_info_on_savepost_save:products.event_definitions.backend.models.property_definition._invalidate_has_person_email_on_savepost_save:products.exports.backend.models.subscription.subscription_saved+post_save:products.feature_flags.backend.flag_version_sync.bump_flag_versions_on_cohort_definition_changepost_save:products.feature_flags.backend.flags_cache.cohort_changed_flags_cachepost_save:products.feature_flags.backend.flags_cache.evaluation_context_changed_flags_cachepost_save:products.feature_flags.backend.flags_cache.experiment_changed_flags_cache@@ -211,6 +212,7 @@ pre_save:products.conversations.backend.signals.handle_comment_soft_deletepre_save:products.signals.backend.receivers.capture_prior_status_for_pr_closepre_save:products.customer_analytics.backend.models.account._enforce_account_group_type_index_drift_policypre_save:products.event_definitions.backend.models.event_definition._capture_event_definition_old_name+pre_save:products.feature_flags.backend.flag_version_sync.capture_cohort_definition_before_savepre_save:products.surveys.backend.models.pre_save_surveyuser_logged_in:posthog.models.activity_logging.signal_handlers.log_user_login_activityuser_logged_in:posthog.models.activity_logging.signal_handlers.post_logindiff --git a/products/feature_flags/backend/apps.py b/products/feature_flags/backend/apps.pyindex 077ddc443a6c..25b8b719df70 100644--- a/products/feature_flags/backend/apps.py+++ b/products/feature_flags/backend/apps.py@@ -18,8 +18,11 @@ class FeatureFlagsConfig(AppConfig):# ride in on the viewset import. Flags are mutated in non-web processes (cohort recalculation# etc.), so its audit logs must wire here too. It lives in a light activity_logging module# because the flag viewset pulls scipy via the dashboard -> error-tracking query runners.+ # flag_version_sync wires here for the same reason: cohort edits happen in+ # non-web processes too, and its version bump must land wherever cohorts save.from products.feature_flags.backend import ( # noqa: F401, PLC0415activity_logging, # noqa: F401, PLC0415+ flag_version_sync,flags_cache,local_evaluation,)diff --git a/products/feature_flags/backend/flag_version_sync.py b/products/feature_flags/backend/flag_version_sync.pynew file mode 100644index 000000000000..39ca05185dd9--- /dev/null+++ b/products/feature_flags/backend/flag_version_sync.py@@ -0,0 +1,217 @@+"""+Bumps FeatureFlag.version when a cohort referenced by the flag changes its conditions.++SDKs consuming the local-evaluation payload use a flag's ``version`` to detect when its+definition changed. A flag's effective definition includes the conditions of every+cohort it references (directly or through nested cohorts), so editing a cohort's+conditions must bump the version of every flag using it — even though the flag rows+themselves didn't change.++Each bump also writes a FeatureFlag activity log entry ("flag history"). That entry is+load-bearing, not just informational: ``version_history.reconstruct_flag_at_version``+rebuilds historical flag states by walking activity entries via their ``version``+change, and raises ``VersionHistoryIncomplete`` for any version number that has no+entry — which is exactly what a silent bump would create.++Membership recalculation bookkeeping must never bump versions: the periodic+recalculation cycle saves every stale dynamic cohort roughly every 15 minutes, and+version churn there would invalidate every SDK cache (and the payload ETag) with no+definition change. The pre_save snapshot plus value comparison below guarantees only+real condition changes bump.+"""++from typing import Any++from django.db import transaction+from django.db.models import Value+from django.db.models.functions import Coalesce+from django.db.models.signals import post_save, pre_save+from django.dispatch import receiver++import structlog++from posthog.exceptions_capture import capture_exception+from posthog.models.activity_logging.activity_log import Change, Detail, LogActivityEntry, Trigger, bulk_log_activity+from posthog.models.activity_logging.utils import activity_storage++from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty+from products.feature_flags.backend.models.feature_flag import FeatureFlag++logger = structlog.get_logger(__name__)++# Also referenced by the frontend flag activity describer — keep the two in sync.+COHORT_CONDITIONS_UPDATED_JOB_TYPE = "cohort_conditions_updated"++# Fields that make up a cohort's conditions. Saves that persist a value change to any+# of these bump the versions of flags referencing the cohort; everything else+# (recalculation bookkeeping, renames, folder moves) must not.+COHORT_DEFINITION_FIELDS = frozenset({"filters", "query", "groups", "is_static"})++_DEFINITION_BEFORE_SAVE_ATTR = "_definition_before_save"+++@receiver(pre_save, sender=Cohort)+def capture_cohort_definition_before_save(+ sender: type[Cohort],+ instance: Cohort,+ raw: bool = False,+ update_fields: frozenset[str] | None = None,+ **kwargs: Any,+) -> None:+ """Snapshot the persisted definition fields this save may overwrite.++ Always resets the snapshot first so a failed earlier save can never leak a stale+ capture into a later save's comparison.+ """+ setattr(instance, _DEFINITION_BEFORE_SAVE_ATTR, None)+ if raw or instance.pk is None:+ return+ # Only fields this save will actually persist: a definition field changed in+ # memory but excluded from update_fields is not written, so it must not count.+ fields = COHORT_DEFINITION_FIELDS if update_fields is None else COHORT_DEFINITION_FIELDS.intersection(update_fields)+ if not fields:+ return+ setattr(instance, _DEFINITION_BEFORE_SAVE_ATTR, Cohort.objects.filter(pk=instance.pk).values(*fields).first())+++@receiver(post_save, sender=Cohort)+def bump_flag_versions_on_cohort_definition_change(+ sender: type[Cohort],+ instance: Cohort,+ created: bool = False,+ raw: bool = False,+ **kwargs: Any,+) -> None:+ if raw or created:+ return+ before = instance.__dict__.pop(_DEFINITION_BEFORE_SAVE_ATTR, None)+ if before is None:+ return+ if all(getattr(instance, field) == value for field, value in before.items()):+ return++ flags = _flags_referencing_cohort(instance)+ if not flags:+ return+ with transaction.atomic():+ # Lock the affected rows (and only them — of="self" keeps the joined team row+ # unlocked) so the versions logged below exactly match what the UPDATE writes+ # even under concurrent flag edits (which take the same lock in the serializer);+ # a mismatched entry breaks version-history reconstruction the same way a+ # missing one does. pk order keeps the lock order consistent.+ old_versions = dict(+ FeatureFlag.objects.filter(pk__in=[flag.pk for flag in flags], team__project_id=instance.team.project_id)+ .select_for_update(of=("self",))+ .order_by("pk")+ .values_list("pk", "version")+ )+ # Bypassing FeatureFlag.save() (and its signals) is intentional: the cohort+ # save already triggers the team's cache invalidation, and the flag rows'+ # own fields are untouched, so updated_at/last_modified_by stay as they were.+ # The flag-history entry the signal path would have produced is written+ # explicitly below instead.+ FeatureFlag.objects.filter(pk__in=old_versions.keys(), team__project_id=instance.team.project_id).update(+ version=Coalesce("version", Value(0)) + 1+ )+ bulk_log_activity(+ [+ _flag_version_bump_entry(flag, old_version=old_versions[flag.pk], cohort=instance)+ for flag in flags+ if flag.pk in old_versions+ ]+ )+++def _flag_version_bump_entry(flag: FeatureFlag, old_version: int | None, cohort: Cohort) -> LogActivityEntry:+ """Build the flag-history entry for a cohort-driven version bump.++ The acting user comes from activity_storage (populated by middleware for API+ requests, i.e. whoever edited the cohort); outside a request the entry is logged+ as a system action.+ """+ return LogActivityEntry(+ organization_id=flag.team.organization_id,+ team_id=flag.team_id,+ user=activity_storage.get_user(),+ was_impersonated=activity_storage.get_was_impersonated(),+ item_id=flag.pk,+ scope="FeatureFlag",+ activity="updated",+ detail=Detail(+ name=flag.key,+ changes=[+ Change(+ type="FeatureFlag",+ action="changed",+ field="version",+ before=old_version,+ after=(old_version or 0) + 1,+ )+ ],+ trigger=Trigger(+ job_type=COHORT_CONDITIONS_UPDATED_JOB_TYPE,+ job_id=str(cohort.pk),+ payload={"cohort_id": cohort.pk, "cohort_name": cohort.name},+ ),+ ),+ )+++def _flags_referencing_cohort(cohort: Cohort) -> list[FeatureFlag]:+ """Non-deleted flags in the cohort's project whose conditions reach this cohort.++ Matches the payload semantics of local evaluation (all non-deleted flags, active or+ not). Mirrors the used_in/deletion-protection lookup in ``posthog/api/cohort.py``,+ which can't be imported here without pulling the API layer into app startup: a+ DB-side pre-filter keeps the Python-side ``get_cohort_ids`` expansion to flags that+ reference some cohort at all — matching any cohort id (not just this one) is+ required, since a flag can reach this cohort transitively through another cohort.+ """+ candidate_flags = list(+ # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (static predicate, no user input)+ FeatureFlag.objects.filter(team__project_id=cohort.team.project_id, deleted=False)+ .extra(where=["""jsonb_path_exists(filters, '$.** ? (@.type == "cohort")')"""])+ .select_related("team")+ )+ # Static cohorts stop the traversal: their membership is a materialized person+ # list, so upstream condition changes don't alter how flags evaluate them.+ seen_cohorts_cache: dict[int, CohortOrEmpty] = {cohort.pk: cohort}+ # Bulk-load every cohort the flags reference directly (the same cohort-property walk+ # get_cohort_ids does), so the expansion below only point-queries cohorts nested+ # behind another cohort's filters. Missing ids are cached as empty so a dangling+ # reference doesn't re-query once per flag either. Guarded per flag: a malformed+ # sibling here must not break the save — the expansion loop below logs it.+ direct_ids: set[int] = set()+ for flag in candidate_flags:+ try:+ for condition in flag.conditions:+ for prop in condition.get("properties", []):+ if prop.get("type") == "cohort" and str(prop.get("value")).lstrip("-").isdigit():+ direct_ids.add(int(prop["value"]))+ except Exception:+ continue+ direct_ids -= seen_cohorts_cache.keys()+ if direct_ids:+ for direct_cohort in Cohort.objects.filter(+ pk__in=direct_ids, team__project_id=cohort.team.project_id, deleted=False+ ):+ seen_cohorts_cache[direct_cohort.pk] = direct_cohort+ for missing_id in direct_ids - seen_cohorts_cache.keys():+ seen_cohorts_cache[missing_id] = ""+ flags: list[FeatureFlag] = []+ for flag in candidate_flags:+ try:+ if cohort.pk in flag.get_cohort_ids(seen_cohorts_cache=seen_cohorts_cache, stop_traversal_at_static=True):+ flags.append(flag)+ except Exception:+ # A sibling flag with malformed filters (e.g. a non-numeric cohort value,+ # which get_cohort_ids doesn't tolerate) must neither break the cohort save+ # nor suppress the bump for healthy flags.+ logger.exception(+ "flag_version_sync_cohort_expansion_failed",+ flag_id=flag.pk,+ cohort_id=cohort.pk,+ team_id=cohort.team_id,+ )+ capture_exception()+ return flagsdiff --git a/products/feature_flags/backend/test/test_flag_version_sync.py b/products/feature_flags/backend/test/test_flag_version_sync.pynew file mode 100644index 000000000000..036a16641fdb--- /dev/null+++ b/products/feature_flags/backend/test/test_flag_version_sync.py@@ -0,0 +1,213 @@+from posthog.test.base import BaseTest++from django.utils import timezone++from parameterized import parameterized++from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.activity_logging.utils import activity_storage++from products.cohorts.backend.models.cohort import Cohort+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.version_history import reconstruct_flag_at_version++# The receivers under test are deliberately not imported here: they must be wired by+# the feature_flags AppConfig, so these tests also fail if that wiring is removed.+++def _updated_entries(flag: FeatureFlag) -> list[ActivityLog]:+ # Flag creation logs a "created" entry via ModelActivityMixin; only "updated"+ # entries are the receiver's output.+ return list(ActivityLog.objects.filter(scope="FeatureFlag", item_id=str(flag.pk), activity="updated"))+++def _person_filters(email: str) -> dict:+ return {+ "properties": {+ "type": "OR",+ "values": [{"type": "OR", "values": [{"key": "email", "value": email, "type": "person"}]}],+ }+ }+++def _cohort_filters(cohort_id: int) -> dict:+ return {+ "properties": {+ "type": "OR",+ "values": [{"type": "OR", "values": [{"key": "id", "value": cohort_id, "type": "cohort"}]}],+ }+ }+++class TestFlagVersionSync(BaseTest):+ def _create_cohort(self, name: str, filters: dict, **kwargs) -> Cohort:+ return Cohort.objects.create(team=self.team, name=name, filters=filters, **kwargs)++ def _create_flag(self, key: str, cohort_id: int) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ key=key,+ created_by=self.user,+ filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort_id}]}]},+ )++ def test_cohort_condition_change_bumps_versions_of_flags_reaching_it(self):+ edited = self._create_cohort("edited", _person_filters("[email protected]"))+ parent = self._create_cohort("parent", _cohort_filters(edited.pk))+ # flag_deeply_nested -> grandparent -> parent -> edited forces the multi-hop+ # dependency traversal (get_all_cohort_dependencies' queue must expand parent,+ # then discover edited on a later iteration) -- the single-level parent case+ # above only does one hop.+ grandparent = self._create_cohort("grandparent", _cohort_filters(parent.pk))+ static_parent = self._create_cohort("static-parent", _cohort_filters(edited.pk), is_static=True)+ unrelated = self._create_cohort("unrelated", _person_filters("[email protected]"))++ flag_direct = self._create_flag("direct", edited.pk)+ flag_nested = self._create_flag("nested", parent.pk)+ flag_deeply_nested = self._create_flag("deeply-nested", grandparent.pk)+ # Static cohorts have materialized membership, so an upstream condition change+ # doesn't alter how flags referencing them evaluate.+ flag_behind_static = self._create_flag("behind-static", static_parent.pk)+ flag_unrelated = self._create_flag("unrelated", unrelated.pk)+ # FeatureFlag.objects already excludes soft-deleted rows, but the candidate+ # query relies on that exclusion to keep deleted flags out of local+ # evaluation's payload semantics -- pin it so a manager change can't+ # silently start bumping deleted flags' versions.+ flag_deleted = self._create_flag("deleted", edited.pk)+ FeatureFlag.objects_including_soft_deleted.filter(pk=flag_deleted.pk).update(deleted=True)+ # Legacy rows can have a NULL version; the bump must produce 1, not NULL.+ FeatureFlag.objects.filter(pk=flag_nested.pk).update(version=None)++ edited.filters = _person_filters("[email protected]")+ edited.save()++ flag_direct.refresh_from_db()+ flag_nested.refresh_from_db()+ flag_deeply_nested.refresh_from_db()+ flag_behind_static.refresh_from_db()+ flag_unrelated.refresh_from_db()+ flag_deleted.refresh_from_db()+ assert flag_direct.version == 2+ assert flag_nested.version == 1+ assert flag_deeply_nested.version == 2+ assert flag_behind_static.version == 1+ assert flag_unrelated.version == 1+ assert flag_deleted.version == 1++ # Every bump writes a flag-history entry whose version change matches the row —+ # version_history reconstruction breaks on versions with no (or a mismatched) entry.+ assert _updated_entries(flag_behind_static) == []+ assert _updated_entries(flag_unrelated) == []+ assert _updated_entries(flag_deleted) == []+ for flag, before, after in ((flag_direct, 1, 2), (flag_nested, None, 1)):+ (entry,) = _updated_entries(flag)+ detail = entry.detail+ assert detail is not None+ assert detail["changes"] == [+ {"type": "FeatureFlag", "action": "changed", "field": "version", "before": before, "after": after}+ ]+ assert detail["trigger"] == {+ "job_type": "cohort_conditions_updated",+ "job_id": str(edited.pk),+ "payload": {"cohort_id": edited.pk, "cohort_name": "edited"},+ }+ assert detail["name"] == flag.key+ # No request context in this test, so the entry is a system action.+ assert entry.user is None+ assert entry.is_system is True++ def test_flag_history_entry_attributes_the_cohort_editor(self):+ cohort = self._create_cohort("cohort", _person_filters("[email protected]"))+ flag = self._create_flag("flag", cohort.pk)+ # Middleware populates activity_storage with the request user; the receiver must+ # attribute the flag-history entry to whoever edited the cohort.+ activity_storage.set_user(self.user)+ self.addCleanup(activity_storage.clear_all)++ cohort.filters = _person_filters("[email protected]")+ cohort.save()++ (entry,) = _updated_entries(flag)+ assert entry.user == self.user+ assert entry.is_system is False++ def test_version_history_reconstructable_across_cohort_driven_bumps(self):+ cohort = self._create_cohort("cohort", _person_filters("[email protected]"))+ original_filters = {"groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}]}]}+ flag = self._create_flag("flag", cohort.pk)++ cohort.filters = _person_filters("[email protected]")+ cohort.save() # version 2, via the receiver++ flag.refresh_from_db()+ flag.filters = {"groups": [{"properties": [], "rollout_percentage": 50}]}+ flag.version = 3+ flag.save() # version 3, via ModelActivityMixin like a regular edit++ # Version 2 exists only because of the cohort bump; without the receiver's+ # activity entry this raised VersionHistoryIncomplete.+ at_v2 = reconstruct_flag_at_version(flag, 2, self.team.pk)+ assert at_v2["version"] == 2+ assert at_v2["filters"] == original_filters+ assert at_v2["is_historical"] is True++ # Undoing the cohort-bump entry must only rewind `version`, never touch other fields.+ at_v1 = reconstruct_flag_at_version(flag, 1, self.team.pk)+ assert at_v1["version"] == 1+ assert at_v1["filters"] == original_filters++ def test_malformed_sibling_flag_does_not_block_save_or_bump(self):+ cohort = self._create_cohort("cohort", _person_filters("[email protected]"))+ healthy_flag = self._create_flag("healthy", cohort.pk)+ # get_cohort_ids raises on non-numeric cohort values; a sibling flag with+ # malformed filters must neither break the cohort save nor stop the bump.+ FeatureFlag.objects.create(+ team=self.team,+ key="malformed",+ created_by=self.user,+ filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": "not-a-number"}]}]},+ )++ cohort.filters = _person_filters("[email protected]")+ cohort.save()++ healthy_flag.refresh_from_db()+ assert healthy_flag.version == 2++ @parameterized.expand(+ [+ ("rename_only_full_save", {"name": "renamed"}, None),+ (+ "recalculation_enqueue_save",+ {"pending_version": 3, "is_calculating": True},+ ["pending_version", "is_calculating"],+ ),+ (+ # The finally-save in calculate_people_ch lists groups and cohort_type+ # in update_fields without changing their values.+ "recalculation_completion_save",+ {"last_calculation": timezone.now(), "errors_calculating": 0},+ ["last_calculation", "errors_calculating", "last_error_at", "cohort_type", "groups"],+ ),+ (+ # A condition field changed in memory but excluded from update_fields+ # is not persisted, so it must not bump either.+ "unpersisted_condition_change",+ {"filters": _person_filters("[email protected]")},+ ["name"],+ ),+ ("unchanged_conditions_full_save", {}, None),+ ]+ )+ def test_non_condition_cohort_saves_do_not_bump_flag_versions(self, _name: str, attrs: dict, update_fields):+ cohort = self._create_cohort("cohort", _person_filters("[email protected]"))+ flag = self._create_flag("flag", cohort.pk)++ for field, value in attrs.items():+ setattr(cohort, field, value)+ cohort.save(update_fields=update_fields) if update_fields is not None else cohort.save()++ flag.refresh_from_db()+ assert flag.version == 1+ # Recalculation bookkeeping must not spam flag history either.+ assert _updated_entries(flag) == []