: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): expose has_experiment in flag definitions (#65275)
Phil Haack5a703b328c89
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex 0c66d2d51d2b..979eca9dda5b 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -788,6 +788,7 @@'__static_attributes__','__str__','_evaluation_tag_names',+ '_has_experiment','_meta','_payloads','_tombstone_suffix',diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex b7fad90170b0..970f5bd91af6 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -73,10 +73,12 @@ post_delete:products.cohorts.backend.models.dependencies.cohort_deletedpost_delete:products.event_definitions.backend.models.event_definition._invalidate_default_event_info_on_deletepost_delete:products.feature_flags.backend.flags_cache.cohort_changed_flags_cachepost_delete:products.feature_flags.backend.flags_cache.evaluation_context_changed_flags_cache+post_delete:products.feature_flags.backend.flags_cache.experiment_changed_flags_cachepost_delete:products.feature_flags.backend.flags_cache.feature_flag_changed_flags_cachepost_delete:products.feature_flags.backend.flags_cache.team_deleted_flags_cachepost_delete:products.feature_flags.backend.local_evaluation.cohort_changedpost_delete:products.feature_flags.backend.local_evaluation.evaluation_context_changed+post_delete:products.feature_flags.backend.local_evaluation.experiment_changedpost_delete:products.feature_flags.backend.local_evaluation.feature_flag_changedpost_delete:products.feature_flags.backend.models.feature_flag.refresh_flag_cache_on_updatespost_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change@@ -156,11 +158,13 @@ post_save:products.event_definitions.backend.models.event_definition._invalidatepost_save:products.exports.backend.models.subscription.subscription_savedpost_save:products.feature_flags.backend.flags_cache.cohort_changed_flags_cachepost_save:products.feature_flags.backend.flags_cache.evaluation_context_changed_flags_cache+post_save:products.feature_flags.backend.flags_cache.experiment_changed_flags_cachepost_save:products.feature_flags.backend.flags_cache.feature_flag_changed_flags_cachepost_save:products.feature_flags.backend.flags_cache.team_created_flags_cachepost_save:products.feature_flags.backend.local_evaluation.cohort_changedpost_save:products.feature_flags.backend.local_evaluation.evaluation_context_changedpost_save:products.feature_flags.backend.local_evaluation.evaluation_context_name_changed+post_save:products.feature_flags.backend.local_evaluation.experiment_changedpost_save:products.feature_flags.backend.local_evaluation.feature_flag_changedpost_save:products.feature_flags.backend.models.feature_flag.refresh_flag_cache_on_updatespost_save:products.product_analytics.backend.models.insight_caching_state.sync_dashboard_tilediff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 3f733aa2c6a2..2db00f222ec8 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -11,6 +11,7 @@ from datetime import datetime, timedeltafrom typing import Any, Optional, castfrom django.conf import settings+from django.contrib.postgres.aggregates import ArrayAggfrom django.db import transactionfrom django.db.models import Count, Prefetch, Q, QuerySet, deletion@@ -2453,6 +2454,35 @@ class MinimalFeatureFlagSerializer(serializers.ModelSerializer):return []+class EvaluationFeatureFlagSerializer(MinimalFeatureFlagSerializer):+ """Flag representation for the SDK-facing evaluation paths: the flags cache the Rust+ service reads (`serialize_feature_flags`) and the local-evaluation response.++ Adds `has_experiment` on top of the minimal flag shape. It lives here rather than on+ MinimalFeatureFlagSerializer so the many UI endpoints that embed the minimal serializer+ (surveys, early access features, product tours, experiments, my_flags) don't each pay a+ per-flag experiment lookup for a field only the SDKs consume.+ """++ has_experiment = serializers.SerializerMethodField(+ help_text=(+ "True if the flag has at least one non-deleted linked experiment. SDKs use this to decide whether "+ "to keep all $feature_flag_called event properties or send a minimal event."+ )+ )++ class Meta(MinimalFeatureFlagSerializer.Meta):+ fields = [*MinimalFeatureFlagSerializer.Meta.fields, "has_experiment"]++ def get_has_experiment(self, feature_flag: FeatureFlag) -> bool:+ # The evaluation/cache batch queries annotate `_has_experiment` via a bulk Exists,+ # so this avoids an N+1. The exists() fallback only fires for unannotated callers.+ cached = getattr(feature_flag, "_has_experiment", None)+ if cached is not None:+ return cached+ return feature_flag.experiment_set.filter(deleted=False).exists()++class MyFlagsResponseSerializer(serializers.Serializer):feature_flag = MinimalFeatureFlagSerializer()value = serializers.JSONField()@@ -2996,12 +3026,24 @@ class FeatureFlagViewSet(FeatureFlag.objects.filter(team__project_id=self.project_id).exclude(Q(id__in=survey_flag_ids)).exclude(Q(id__in=product_tour_internal_targeting_flags))+ .annotate(+ evaluation_tag_names_agg=ArrayAgg(+ "flag_evaluation_contexts__evaluation_context__name",+ filter=Q(flag_evaluation_contexts__isnull=False),+ distinct=True,+ ),+ ).order_by("-created_at"))if not feature_flags:return Response([])+ # Transfer the bulk-aggregated context names onto _evaluation_tag_names so the+ # serializer answers without a per-flag query (see get_evaluation_contexts).+ for flag in feature_flags:+ flag._evaluation_tag_names = getattr(flag, "evaluation_tag_names_agg", None)+groups = request.validated_query_data.get("groups", {})# Ensure groups is always a dict, not a stringif isinstance(groups, str):diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 0fd99ee3e0fe..7ea3e4be6b2e 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -10154,6 +10154,31 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):self.assertIsNotNone(cached_flag.evaluation_tag_names)self.assertEqual(cached_flag.evaluation_tag_names, ["app"])+ @parameterized.expand([("with_experiment", True), ("without_experiment", False)])+ @pytest.mark.ee+ def test_has_experiment_survives_cache_round_trip(self, _name: str, has_experiment: bool):+ from products.feature_flags.backend.models.feature_flag import (+ get_feature_flags_for_team_in_cache,+ set_feature_flags_for_team_in_cache,+ )++ flag = FeatureFlag.objects.create(+ team=self.team,+ key="round-trip-flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ created_by=self.user,+ )+ if has_experiment:+ Experiment.objects.create(team=self.team, name="exp", feature_flag=flag)++ set_feature_flags_for_team_in_cache(self.team.project_id)+ cached_flags = get_feature_flags_for_team_in_cache(self.team.project_id)++ assert cached_flags is not None+ cached_flag = next(f for f in cached_flags if f.key == "round-trip-flag")+ # The cached value is read back without a per-flag experiment query.+ self.assertEqual(cached_flag._has_experiment, has_experiment)+@pytest.mark.eedef test_evaluation_contexts_cache_invalidation(self):from products.feature_flags.backend.models.feature_flag import (diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex ce471e1ef95d..31614ebcb5ba 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -62,6 +62,7 @@ from posthog.storage.hypercache_manager import (from products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.dependencies import extract_cohort_dependencies+from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.flags_cache_messages import FlagsCacheInvalidationfrom products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags, serialize_feature_flags@@ -391,13 +392,15 @@ def _get_feature_flags_for_teams_batch(teams: list[Team]) -> dict[int, dict[str,"flag_evaluation_contexts__evaluation_context__name",filter=Q(flag_evaluation_contexts__isnull=False),distinct=True,- )+ ),+ has_experiment_agg=Exists(Experiment.objects.filter(feature_flag_id=OuterRef("pk"), deleted=False)),))# Transfer aggregated tag names to model instancesfor flag in all_flags:flag._evaluation_tag_names = flag.evaluation_tag_names_agg or []+ flag._has_experiment = flag.has_experiment_agg# Group flags by team_idflags_by_team_id: dict[int, list[FeatureFlag]] = defaultdict(list)@@ -1041,6 +1044,28 @@ def feature_flag_changed_flags_cache(sender, instance: "FeatureFlag", **kwargs):transaction.on_commit(lambda: _enqueue_invalidation(team_id))+@receiver(post_save, sender=Experiment)+@receiver(post_delete, sender=Experiment)+def experiment_changed_flags_cache(sender, instance: "Experiment", **kwargs):+ """+ Invalidate flags cache when an experiment is created, soft-deleted, or removed.++ A flag's cached `has_experiment` depends on whether it has any non-deleted linked+ experiment, so experiment changes must refresh the linked flag's team cache.+ Keyed on the experiment's own team_id, which also covers experiment reassignment+ between flags within the team. Only operates when FLAGS_REDIS_URL is configured.++ Fires on every save by design, mirroring feature_flag_changed_flags_cache: Experiment+ rows are only written on user-driven lifecycle/edit operations (no high-churn periodic+ path touches them, unlike cohort recalculation), so an update_fields gate isn't warranted.+ """+ if not settings.FLAGS_REDIS_URL:+ return++ team_id = instance.team_id+ transaction.on_commit(lambda: _enqueue_invalidation(team_id))++@receiver(post_save, sender=Team)def team_created_flags_cache(sender, instance: "Team", created: bool, **kwargs):"""diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex 97d65075d7e3..6f3f6b7f5703 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -28,7 +28,7 @@ from typing import Any, Union, castfrom django.conf import settingsfrom django.contrib.postgres.aggregates import ArrayAggfrom django.db import transaction-from django.db.models import Q+from django.db.models import Exists, OuterRef, Qfrom django.db.models.signals import post_delete, post_savefrom django.dispatch import receiver@@ -50,6 +50,7 @@ from posthog.utils import capture_exception_throttled, get_safe_cachefrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, is_cohort_recalculation_only_savefrom products.cohorts.backend.models.util import get_nested_cohort_ids+from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.flags_cache import (_compare_flag_fields,get_team_ids_with_recently_updated_flags,@@ -576,7 +577,7 @@ def _get_flags_response_for_local_evaluation_batch(query each regardless of team count), then iterates the materialized flaglist with itertools.groupby to process one team at a time."""- from products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializer+ from products.feature_flags.backend.api.feature_flag import EvaluationFeatureFlagSerializerif not teams:return {}@@ -611,7 +612,8 @@ def _get_flags_response_for_local_evaluation_batch("flag_evaluation_contexts__evaluation_context__name",filter=Q(flag_evaluation_contexts__isnull=False),distinct=True,- )+ ),+ has_experiment_agg=Exists(Experiment.objects.filter(feature_flag_id=OuterRef("pk"), deleted=False)),).order_by("team_id", "key"))@@ -619,6 +621,7 @@ def _get_flags_response_for_local_evaluation_batch(referenced_cohort_ids: set[int] = set()for flag in all_flags:flag._evaluation_tag_names = flag.evaluation_tag_names_agg or []+ flag._has_experiment = flag.has_experiment_aggreferenced_cohort_ids.update(_extract_cohort_ids_from_filters(flag.filters or {}))# Load only the referenced cohorts and resolve nested dependencies@@ -699,7 +702,7 @@ def _get_flags_response_for_local_evaluation_batch(else:feature_flag.filters = filters- flags_data.append(MinimalFeatureFlagSerializer(feature_flag, context={}).data)+ flags_data.append(EvaluationFeatureFlagSerializer(feature_flag, context={}).data)if include_cohorts:for cohort_id in cohort_ids:@@ -941,6 +944,19 @@ def feature_flag_changed(sender, instance: "FeatureFlag", **kwargs):transaction.on_commit(lambda: update_team_flags_cache.delay(instance.team_id))+@receiver(post_save, sender=Experiment)+@receiver(post_delete, sender=Experiment)+def experiment_changed(sender, instance: "Experiment", **kwargs):+ # A flag's local-eval `has_experiment` depends on whether it has any non-deleted+ # linked experiment, so experiment changes must refresh the linked flag's team cache.+ # Fires on every save by design, mirroring feature_flag_changed: Experiment rows are+ # only written on user-driven lifecycle/edit operations (no high-churn periodic path+ # touches them), so an update_fields gate isn't warranted here.+ from products.feature_flags.backend.tasks import update_team_flags_cache++ transaction.on_commit(lambda: update_team_flags_cache.delay(instance.team_id))++@receiver(post_save, sender=Cohort)@receiver(post_delete, sender=Cohort)def cohort_changed(sender, instance: "Cohort", **kwargs):diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex 767552f5f73c..cc8e7b75f053 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -7,7 +7,7 @@ from django.contrib.postgres.aggregates import ArrayAggfrom django.core.cache import cachefrom django.core.exceptions import ValidationErrorfrom django.db import DatabaseError, models, transaction-from django.db.models import Q, QuerySet+from django.db.models import Exists, OuterRef, Q, QuerySetfrom django.db.models.signals import post_delete, post_savefrom django.http import HttpRequestfrom django.utils import timezone@@ -28,6 +28,7 @@ from posthog.models.signals import mutable_receiverfrom posthog.models.utils import RootTeamManager, RootTeamMixinfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty+from products.experiments.backend.models.experiment import ExperimentFIVE_DAYS = 60 * 60 * 24 * 5 # 5 days in seconds@@ -135,6 +136,10 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models# when accessing evaluation context names for many flags at once._evaluation_tag_names: Optional[list[str]] = None+ # Cache projection: whether the flag backs an experiment. Annotated via a bulk+ # Exists query (or read from cache) to avoid a per-flag experiment lookup.+ _has_experiment: Optional[bool] = None+last_called_at = models.DateTimeField(null=True,blank=True,@@ -659,7 +664,8 @@ def get_feature_flags("flag_evaluation_contexts__evaluation_context__name",filter=Q(flag_evaluation_contexts__isnull=False),distinct=True,- )+ ),+ has_experiment_agg=Exists(Experiment.objects.filter(feature_flag_id=OuterRef("pk"), deleted=False)),)all_feature_flags = list(qs)@@ -674,6 +680,7 @@ def get_feature_flags(except AttributeError:# evaluation_tag_names_agg field missing from aggregation query_flag._evaluation_tag_names = None+ _flag._has_experiment = _flag.has_experiment_aggreturn all_feature_flags@@ -688,9 +695,9 @@ def serialize_feature_flags(flags: list[FeatureFlag]) -> list[dict[str, Any]]:Returns:List of serialized flag dictionaries"""- from products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializer+ from products.feature_flags.backend.api.feature_flag import EvaluationFeatureFlagSerializer- serialized_data = MinimalFeatureFlagSerializer(flags, many=True).data+ serialized_data = EvaluationFeatureFlagSerializer(flags, many=True).datareturn list(serialized_data)@@ -747,10 +754,11 @@ def _feature_flag_model_field_names() -> frozenset[str]:def _feature_flag_from_cache_entry(entry: dict[str, Any]) -> FeatureFlag:"""Reconstruct a FeatureFlag from one cached payload entry.- The cache payload comes from MinimalFeatureFlagSerializer, which emits- SerializerMethodFields (e.g. `evaluation_contexts`) that are not model fields.- Keep only real model fields so unknown extras are ignored rather than crashing- the FeatureFlag(**...) constructor; known extras are then assigned onto the instance.+ The cache payload comes from EvaluationFeatureFlagSerializer, which emits+ SerializerMethodFields (e.g. `evaluation_contexts`, `has_experiment`) that are not+ model fields. Keep only real model fields so unknown extras are ignored rather than+ crashing the FeatureFlag(**...) constructor; known extras are then assigned onto the+ instance."""model_field_names = _feature_flag_model_field_names()model_fields = {key: value for key, value in entry.items() if key in model_field_names}@@ -760,6 +768,8 @@ def _feature_flag_from_cache_entry(entry: dict[str, Any]) -> FeatureFlag:# `evaluation_contexts` key and the legacy `evaluation_tags` key for entries# written before the rename.flag._evaluation_tag_names = entry.get("evaluation_contexts", entry.get("evaluation_tags"))+ # Preserve has_experiment so a cache-read flag answers without a per-flag experiment query.+ flag._has_experiment = entry.get("has_experiment")return flagdiff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex 9276cf908e53..d803ed96b05a 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -20,7 +20,9 @@ from unittest.mock import MagicMock, patchfrom django.conf import settingsfrom django.core.management.base import OutputWrapper+from django.db import connectionfrom django.test import override_settings+from django.test.utils import CaptureQueriesContextfrom parameterized import parameterized@@ -28,6 +30,7 @@ from posthog.kafka_client.topics import KAFKA_FLAGS_CACHE_INVALIDATIONfrom posthog.models import Teamfrom products.cohorts.backend.models.cohort import Cohort+from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.flags_cache import (_compare_flag_fields,_compute_flag_dependencies,@@ -541,6 +544,77 @@ class TestServiceFlagsCache(BaseTest):assert result[other_team.id]["cohorts"][0]["id"] == cohort_b.id+@override_settings(FLAGS_REDIS_URL="redis://test")+class TestHasExperimentField(BaseTest):+ """has_experiment reflects whether a flag has a non-deleted linked experiment."""++ def setUp(self):+ super().setUp()+ clear_flags_cache(self.team, kinds=["redis", "s3"])++ def _make_flag(self, key: str) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ key=key,+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ @parameterized.expand(+ [+ ("no_experiment", "none", False),+ ("active_experiment", "active", True),+ ("stopped_not_deleted_experiment", "stopped", True),+ ("deleted_experiment", "deleted", False),+ ]+ )+ def test_has_experiment_value(self, _name: str, experiment_state: str, expected: bool):+ flag = self._make_flag("exp-flag")+ if experiment_state == "active":+ Experiment.objects.create(team=self.team, name="exp", feature_flag=flag)+ elif experiment_state == "stopped":+ Experiment.objects.create(team=self.team, name="exp", feature_flag=flag, end_date=datetime.now(UTC))+ elif experiment_state == "deleted":+ Experiment.objects.create(team=self.team, name="exp", feature_flag=flag, deleted=True)++ flags = _get_feature_flags_for_service(self.team)["flags"]+ assert flags[0]["has_experiment"] is expected++ def test_has_experiment_present_in_batch_output(self):+ flag = self._make_flag("exp-flag")+ Experiment.objects.create(team=self.team, name="exp", feature_flag=flag)++ flags = _get_feature_flags_for_teams_batch([self.team])[self.team.id]["flags"]+ assert flags[0]["has_experiment"] is True++ def test_has_experiment_no_n_plus_one(self):+ """has_experiment is computed via a bulk Exists subquery, so the number of queries+ touching the experiment table stays constant as flags/experiments grow. Counting only+ experiment-table queries isolates this from unrelated per-flag queries on other paths."""++ def experiment_query_count(ctx: CaptureQueriesContext) -> int:+ return sum(1 for q in ctx.captured_queries if "posthog_experiment" in q["sql"])++ first = self._make_flag("flag-0")+ Experiment.objects.create(team=self.team, name="exp-0", feature_flag=first)++ with CaptureQueriesContext(connection) as baseline:+ _get_feature_flags_for_service(self.team)++ for i in range(1, 6):+ extra = self._make_flag(f"flag-{i}")+ Experiment.objects.create(team=self.team, name=f"exp-{i}", feature_flag=extra)++ with CaptureQueriesContext(connection) as scaled:+ _get_feature_flags_for_service(self.team)++ assert experiment_query_count(scaled) == experiment_query_count(baseline), (+ f"Experiment-table query count grew from {experiment_query_count(baseline)} to "+ f"{experiment_query_count(scaled)} as flags/experiments were added — "+ "indicates an N+1 in the has_experiment computation."+ )++@override_settings(FLAGS_REDIS_URL="redis://test")class TestServiceFlagsSignals(BaseTest):"""Test Django signal handlers for automatic cache invalidation."""@@ -604,6 +678,33 @@ class TestServiceFlagsSignals(BaseTest):# Signal should trigger the Celery taskmock_task.delay.assert_called_once_with(self.team.id)+ @parameterized.expand(["create", "soft_delete", "delete"])+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_signal_fired_on_experiment_change(self, action, mock_task):+ # Creating, soft-deleting, or hard-deleting an experiment invalidates the linked+ # flag's team cache so has_experiment refreshes.+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="exp-flag",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ if action == "create":+ # Reset first so we assert on the experiment-create signal, not the flag-create one.+ mock_task.reset_mock()+ Experiment.objects.create(team=self.team, name="My experiment", feature_flag=flag)+ else:+ experiment = Experiment.objects.create(team=self.team, name="My experiment", feature_flag=flag)+ mock_task.reset_mock()+ if action == "soft_delete":+ experiment.deleted = True+ experiment.save()+ else:+ experiment.delete()++ mock_task.delay.assert_called_once_with(self.team.id)+@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_fired_on_team_create(self, mock_task):diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex 391f20787fd8..3d97cba7485e 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -19,6 +19,7 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom posthog.utils import safe_cache_deletefrom products.cohorts.backend.models.cohort import Cohort+from products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.flags_cache import get_team_ids_with_recently_updated_flagsfrom products.feature_flags.backend.local_evaluation import (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,@@ -400,6 +401,30 @@ class TestUpdateFlagCachesGroupMappingGuards(BaseTest):class TestLocalEvaluationSignals(BaseTest):+ @parameterized.expand(["create", "soft_delete", "delete"])+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_signal_fired_on_experiment_change(self, action, mock_task):+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="exp-flag",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ if action == "create":+ mock_task.reset_mock()+ Experiment.objects.create(team=self.team, name="My experiment", feature_flag=flag)+ else:+ experiment = Experiment.objects.create(team=self.team, name="My experiment", feature_flag=flag)+ mock_task.reset_mock()+ if action == "soft_delete":+ experiment.deleted = True+ experiment.save()+ else:+ experiment.delete()++ mock_task.delay.assert_called_once_with(self.team.id)+@patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())def test_signal_fired_on_evaluation_context_association_create(self, mock_task):diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rsindex e61011e11110..3f0ed80b2d8c 100644--- a/rust/feature-flags/src/api/types.rs+++ b/rust/feature-flags/src/api/types.rs@@ -439,6 +439,10 @@ pub struct FlagDetailsMetadata {pub version: i32,pub description: Option<String>,pub payload: Option<Value>,+ /// True if the flag has at least one non-deleted linked experiment. SDKs use this to+ /// decide whether to keep all $feature_flag_called event properties or send a minimal event.+ #[serde(default)]+ pub has_experiment: bool,}#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]@@ -489,6 +493,7 @@ impl FromFeatureAndMatch for FlagDetails {version: flag.version.unwrap_or(0),description: None,payload: flag_match.payload.clone(),+ has_experiment: flag.has_experiment,},conditions: if detailed_analysis {Some(Self::build_condition_analysis(@@ -519,6 +524,7 @@ impl FromFeatureAndMatch for FlagDetails {version: flag.version.unwrap_or(0),description: None,payload: None,+ has_experiment: flag.has_experiment,},conditions: None,}@@ -1037,6 +1043,7 @@ mod tests {version: 1,description: None,payload: Some(json!({"key": "value"})),+ has_experiment: false,},conditions: None,},@@ -1060,6 +1067,7 @@ mod tests {version: 1,description: None,payload: None,+ has_experiment: false,},conditions: None,},@@ -1083,6 +1091,7 @@ mod tests {version: 1,description: None,payload: Some(Value::Null),+ has_experiment: false,},conditions: None,},diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rsindex b8f482f2e1dd..b0df769a33e7 100644--- a/rust/feature-flags/src/flags/feature_flag_list.rs+++ b/rust/feature-flags/src/flags/feature_flag_list.rs@@ -2,8 +2,8 @@ use crate::api::errors::FlagError;use crate::cohorts::cohort_models::Cohort;use crate::database::get_connection_with_metrics;use crate::flags::flag_models::{- EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow, FlagPropertyGroup,- HypercacheFlagsWrapper,+ default_has_experiment, EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow,+ FlagPropertyGroup, HypercacheFlagsWrapper,};use crate::metrics::consts::TOMBSTONE_COUNTER;use common_database::PostgresReader;@@ -194,6 +194,9 @@ impl FeatureFlagList {evaluation_runtime: row.evaluation_runtime,evaluation_tags: row.evaluation_tags,bucketing_identifier: row.bucketing_identifier,+ // The PG fallback query doesn't compute experiment linkage, so fall back+ // to the shared default (true) for this rare, transient cache-miss path.+ has_experiment: default_has_experiment(),}),Err(e) => {// This is highly unlikely to happen, but if it does, we skip the flag.@@ -638,6 +641,7 @@ mod tests {team_id: 123,name: Some("Test Flag".to_string()),key: "test_flag".to_string(),+ has_experiment: false,filters: FlagFilters::default(),deleted: false,active: true,@@ -1208,6 +1212,7 @@ mod tests {team_id: 1,name: None,key: "test_flag".to_string(),+ has_experiment: false,filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![@@ -1321,6 +1326,7 @@ mod tests {team_id: 123,name: Some("Serialization Test".to_string()),key: "serialize_test".to_string(),+ has_experiment: false,filters: FlagFilters::default(),deleted: false,active: true,diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rsindex 7ed5d23d0bf0..721939d2e824 100644--- a/rust/feature-flags/src/flags/flag_matching.rs+++ b/rust/feature-flags/src/flags/flag_matching.rs@@ -16,7 +16,8 @@ use crate::flags::flag_matching_utils::{should_write_hash_key_override,};use crate::flags::flag_models::{- FeatureFlag, FeatureFlagId, FeatureFlagList, FlagFilters, FlagPropertyGroup,+ default_has_experiment, FeatureFlag, FeatureFlagId, FeatureFlagList, FlagFilters,+ FlagPropertyGroup,};use crate::flags::flag_operations::flags_require_db_preparation;use crate::handler::canonical_log::{install_rayon_canonical_log, take_rayon_canonical_log};@@ -1176,6 +1177,8 @@ impl FeatureFlagMatcher {let stub = FeatureFlag {id: snapshot.id,key: snapshot.key,+ // Panic fallback can't compute experiment linkage; use the shared default.+ has_experiment: default_has_experiment(),active: true,version: snapshot.version,filters: FlagFilters::default(),diff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rsindex 403ed5b7ea07..39ed2d4863ee 100644--- a/rust/feature-flags/src/flags/flag_models.rs+++ b/rust/feature-flags/src/flags/flag_models.rs@@ -280,6 +280,24 @@ pub struct FeatureFlag {pub evaluation_tags: Option<Vec<String>>,#[serde(default, skip_serializing_if = "Option::is_none")]pub bucketing_identifier: Option<String>,+ /// True if the flag has at least one non-deleted linked experiment. Surfaced to+ /// SDKs via FlagDetailsMetadata so they can decide whether to keep or strip+ /// $feature_flag_called event properties.+ ///+ /// Defaults to `true` (rather than the usual `#[serde(default)]` bool false) so cache+ /// entries written by older Django without the field over-preserve properties instead of+ /// stripping them. A spurious `true` only wastes bytes; a spurious `false` would strip+ /// unrecoverable experiment-exposure data. The fallback query paths share this default via+ /// `default_has_experiment()`.+ #[serde(default = "default_has_experiment")]+ pub has_experiment: bool,+}++/// Default for `FeatureFlag::has_experiment` when experiment linkage is unknowable — an+/// older-Django cache payload missing the field, or a fallback query path that can't compute+/// it. See the field doc for why this is `true` rather than `false`.+pub(crate) fn default_has_experiment() -> bool {+ true}impl FeatureFlag {diff --git a/rust/feature-flags/src/flags/flag_service.rs b/rust/feature-flags/src/flags/flag_service.rsindex 06729c8c99ff..c4416b4ef21f 100644--- a/rust/feature-flags/src/flags/flag_service.rs+++ b/rust/feature-flags/src/flags/flag_service.rs@@ -431,6 +431,7 @@ mod tests {team_id: team.id,name: Some("Beta Feature".to_string()),key: "beta_feature".to_string(),+ has_experiment: false,filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {@@ -468,6 +469,7 @@ mod tests {team_id: team.id,name: Some("New User Interface".to_string()),key: "new_ui".to_string(),+ has_experiment: false,filters: FlagFilters {groups: vec![],multivariate: None,@@ -491,6 +493,7 @@ mod tests {team_id: team.id,name: Some("Premium Feature".to_string()),key: "premium_feature".to_string(),+ has_experiment: false,filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: Some(vec![PropertyFilter {@@ -622,6 +625,7 @@ mod tests {team_id: team.id,name: Some(format!("Test Flag {i} with a longer name for size")),key: format!("test_flag_{i}_with_extra_chars_for_larger_payload"),+ has_experiment: false,deleted: false,active: i % 2 == 0,filters: FlagFilters {diff --git a/rust/feature-flags/src/flags/test_flag_matching.rs b/rust/feature-flags/src/flags/test_flag_matching.rsindex 0b7bea07ff62..f9cd4441feea 100644--- a/rust/feature-flags/src/flags/test_flag_matching.rs+++ b/rust/feature-flags/src/flags/test_flag_matching.rs@@ -4354,6 +4354,7 @@ mod tests {team_id: team.id,name: Some("Beta feature".to_string()),key: "beta-feature".to_string(),+ has_experiment: false,filters: FlagFilters {groups: vec![FlagPropertyGroup {properties: None,@@ -5673,6 +5674,7 @@ mod tests {team_id: team.id,name: Some("Test Order Flag".to_string()),key: "test_order_flag".to_string(),+ has_experiment: false,filters: FlagFilters {groups: vec![FlagPropertyGroup {diff --git a/rust/feature-flags/src/handler/body_logger.rs b/rust/feature-flags/src/handler/body_logger.rsindex 26d0962a735b..9014cabf97d3 100644--- a/rust/feature-flags/src/handler/body_logger.rs+++ b/rust/feature-flags/src/handler/body_logger.rs@@ -366,6 +366,7 @@ mod tests {version: 1,description: None,payload: None,+ has_experiment: false,},conditions: None,}diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rsindex b727c61e979e..bb0564b03544 100644--- a/rust/feature-flags/src/handler/tests.rs+++ b/rust/feature-flags/src/handler/tests.rs@@ -332,6 +332,7 @@ async fn test_evaluate_feature_flags_with_errors() {version: 1,description: None,payload: None,+ has_experiment: false,},conditions: None,}@@ -798,6 +799,7 @@ async fn test_evaluate_feature_flags_details() {version: 1,description: None,payload: None,+ has_experiment: false,},conditions: None,}@@ -819,6 +821,7 @@ async fn test_evaluate_feature_flags_details() {version: 1,description: None,payload: None,+ has_experiment: false,},conditions: None,}diff --git a/rust/feature-flags/src/utils/mock.rs b/rust/feature-flags/src/utils/mock.rsindex 62f135196b06..321b7bcc82eb 100644--- a/rust/feature-flags/src/utils/mock.rs+++ b/rust/feature-flags/src/utils/mock.rs@@ -319,6 +319,7 @@ mod tests {name: Some("Test Flag".to_string()),id: 1,key: "test_flag".to_string(),+ has_experiment: false,active: true,deleted: false,team_id: 99,diff --git a/rust/feature-flags/tests/fixtures/hypercache_contract.json b/rust/feature-flags/tests/fixtures/hypercache_contract.jsonindex fd436cbd45e9..10988b1c97d0 100644--- a/rust/feature-flags/tests/fixtures/hypercache_contract.json+++ b/rust/feature-flags/tests/fixtures/hypercache_contract.json@@ -5,6 +5,7 @@"team_id": 99,"name": "Full feature flag with all optional fields","key": "full-flag",+ "has_experiment": false,"filters": {"groups": [{@@ -61,6 +62,7 @@"team_id": 99,"name": "","key": "minimal-flag",+ "has_experiment": false,"filters": {"groups": [{@@ -85,6 +87,7 @@"team_id": 99,"name": "Cohort flag","key": "cohort-flag",+ "has_experiment": false,"filters": {"groups": [{@@ -116,6 +119,7 @@"team_id": 99,"name": "Flag with dependency","key": "dependent-flag",+ "has_experiment": false,"filters": {"groups": [{@@ -148,6 +152,7 @@"team_id": 99,"name": "Flag with missing dependency","key": "missing-dep-flag",+ "has_experiment": false,"filters": {"groups": [{