Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(surveys): route survey flag maintenance through the flag facade (#71363)

Anderseaf1ac2805f4
diff --git a/posthog/tasks/test/test_update_survey_adaptive_sampling.py b/posthog/tasks/test/test_update_survey_adaptive_sampling.py
index c1ef18a7b636..2600ee318de2 100644
--- a/posthog/tasks/test/test_update_survey_adaptive_sampling.py
+++ b/posthog/tasks/test/test_update_survey_adaptive_sampling.py
@@ -1,4 +1,5 @@
import json
+from copy import deepcopy
from datetime import datetime
from freezegun import freeze_time
@@ -7,8 +8,13 @@ from unittest.mock import MagicMock, patch
from django.utils import timezone
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.tasks.update_survey_adaptive_sampling import update_survey_adaptive_sampling
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.surveys.backend.models import Survey
@@ -81,6 +87,98 @@ class TestUpdateSurveyAdaptiveSampling(BaseTest):
self.assertEqual(internal_response_sampling_flag.filters["groups"][0]["rollout_percentage"], 100)
mock_get_count.assert_not_called()
+ @parameterized.expand(
+ [
+ (
+ "sampling_flag_shape",
+ {"groups": [{"variant": "", "rollout_percentage": 100, "properties": []}]},
+ ),
+ (
+ "targeting_shape_with_internal_properties",
+ {
+ "groups": [
+ {
+ "variant": "",
+ "rollout_percentage": 100,
+ "properties": [
+ {
+ "key": "$survey_dismissed/0192e-abc",
+ "value": "is_not_set",
+ "operator": "is_not_set",
+ "type": "person",
+ },
+ {
+ "key": "$survey_responded/0192e-abc",
+ "value": "is_not_set",
+ "operator": "is_not_set",
+ "type": "person",
+ },
+ {
+ "key": "$survey_last_seen_date",
+ "value": "30d",
+ "operator": "is_date_before",
+ "type": "person",
+ },
+ ],
+ },
+ {"variant": "", "rollout_percentage": 100, "properties": []},
+ ]
+ },
+ ),
+ ]
+ )
+ @freeze_time("2024-12-13T12:00:00Z")
+ @patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")
+ def test_round_trip_preserves_filters_except_rollout(
+ self, _name: str, filters: dict, mock_get_count: MagicMock
+ ) -> None:
+ self.internal_response_sampling_flag.filters = filters
+ self.internal_response_sampling_flag.save()
+ expected = deepcopy(filters)
+ expected["groups"][0]["rollout_percentage"] = 20
+ # The serializer normalizes aggregation onto every condition set (None = person-aggregated)
+ for group in expected["groups"]:
+ group["aggregation_group_type_index"] = None
+ expected["aggregation_group_type_index"] = None
+
+ mock_get_count.return_value = 50
+ update_survey_adaptive_sampling()
+
+ internal_response_sampling_flag = FeatureFlag.objects.get(id=self.internal_response_sampling_flag.id)
+ self.assertEqual(internal_response_sampling_flag.filters, expected)
+
+ @freeze_time("2024-12-13T12:00:00Z")
+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+ @patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")
+ def test_system_write_skips_approval_gate_and_logs_system_activity(
+ self, mock_get_count: MagicMock, _mock_enabled: MagicMock
+ ) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}
+ ]
+ self.organization.save()
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.update",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+ mock_get_count.return_value = 50
+
+ with self.captureOnCommitCallbacks(execute=True):
+ update_survey_adaptive_sampling()
+
+ internal_response_sampling_flag = FeatureFlag.objects.get(id=self.internal_response_sampling_flag.id)
+ self.assertEqual(internal_response_sampling_flag.filters["groups"][0]["rollout_percentage"], 20)
+ self.assertFalse(ChangeRequest.objects.filter(team=self.team).exists())
+ log = ActivityLog.objects.get(
+ scope="FeatureFlag", item_id=str(internal_response_sampling_flag.id), activity="updated"
+ )
+ self.assertTrue(log.is_system)
+ self.assertIsNone(log.user)
+
@patch("posthog.tasks.update_survey_adaptive_sampling._get_survey_responses_count")
def test_ignores_surveys_without_limits(self, mock_get_count: MagicMock) -> None:
self.survey.response_sampling_limit = 0
diff --git a/posthog/tasks/test/test_update_survey_iteration.py b/posthog/tasks/test/test_update_survey_iteration.py
index e25c77bdd65a..93cdc58f72fd 100644
--- a/posthog/tasks/test/test_update_survey_iteration.py
+++ b/posthog/tasks/test/test_update_survey_iteration.py
@@ -1,14 +1,17 @@
from datetime import datetime, timedelta
from posthog.test.base import ClickhouseTestMixin
+from unittest.mock import MagicMock, patch
from django.test import TestCase
from django.utils.timezone import now
+from posthog.constants import AvailableFeature
from posthog.models import Organization, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.tasks.update_survey_iteration import update_survey_iteration
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.surveys.backend.models import Survey
@@ -108,31 +111,7 @@ class TestUpdateSurveyIteration(TestCase, ClickhouseTestMixin):
self.assertEqual(self.recurring_survey.current_iteration, 3)
assert self.recurring_survey.internal_targeting_flag is not None
- self.assertLessEqual(
- {
- "groups": [
- {
- "variant": "",
- "properties": [
- {
- "key": f"$survey_dismissed/{self.recurring_survey.id}/3",
- "type": "person",
- "value": "is_not_set",
- "operator": "is_not_set",
- },
- {
- "key": f"$survey_responded/{self.recurring_survey.id}/3",
- "type": "person",
- "value": "is_not_set",
- "operator": "is_not_set",
- },
- ],
- "rollout_percentage": 100,
- }
- ]
- }.items(),
- self.recurring_survey.internal_targeting_flag.filters.items(),
- )
+ self.assertEqual(self.recurring_survey.internal_targeting_flag.filters, self._expected_iteration_filters(3))
def test_can_create_internal_targeting_flag(self) -> None:
self.recurring_survey.start_date = now() - timedelta(self.iteration_frequency_days * 3)
@@ -145,33 +124,7 @@ class TestUpdateSurveyIteration(TestCase, ClickhouseTestMixin):
self.assertEqual(self.recurring_survey.current_iteration, 3)
internal_flag = FeatureFlag.objects.get(key=self.recurring_survey.id)
- assert internal_flag is not None
- if internal_flag is not None:
- self.assertLessEqual(
- {
- "groups": [
- {
- "variant": "",
- "properties": [
- {
- "key": f"$survey_dismissed/{self.recurring_survey.id}/3",
- "type": "person",
- "value": "is_not_set",
- "operator": "is_not_set",
- },
- {
- "key": f"$survey_responded/{self.recurring_survey.id}/3",
- "type": "person",
- "value": "is_not_set",
- "operator": "is_not_set",
- },
- ],
- "rollout_percentage": 100,
- }
- ]
- }.items(),
- internal_flag.filters.items(),
- )
+ self.assertEqual(internal_flag.filters, self._expected_iteration_filters(3))
def test_iteration_change_updates_flag_with_new_iteration_suffix(self) -> None:
"""Test that when iteration changes, the flag is updated with the NEW iteration suffix.
@@ -214,14 +167,95 @@ class TestUpdateSurveyIteration(TestCase, ClickhouseTestMixin):
self.recurring_survey.refresh_from_db()
self.assertEqual(self.recurring_survey.current_iteration, 3)
- # Verify flag now has NEW iteration suffix (/3), not old (/1)
+ # Verify flag now has NEW iteration suffix (/3), not old (/1), and that
+ # nothing else was added or dropped on the way through the flag facade
assert self.recurring_survey.internal_targeting_flag is not None
self.recurring_survey.internal_targeting_flag.refresh_from_db()
flag_filters = self.recurring_survey.internal_targeting_flag.filters
- properties = flag_filters["groups"][0]["properties"]
- property_keys = [p["key"] for p in properties]
- self.assertIn(f"$survey_dismissed/{self.recurring_survey.id}/3", property_keys)
- self.assertIn(f"$survey_responded/{self.recurring_survey.id}/3", property_keys)
- self.assertNotIn(f"$survey_dismissed/{self.recurring_survey.id}/1", property_keys)
- self.assertNotIn(f"$survey_responded/{self.recurring_survey.id}/1", property_keys)
+ self.assertEqual(flag_filters, self._expected_iteration_filters(3))
+
+ def _expected_iteration_filters(self, iteration: int) -> dict:
+ # aggregation_group_type_index (None = person-aggregated) is normalized onto
+ # every condition set by the flag serializer on the way through the facade
+ return {
+ "groups": [
+ {
+ "variant": "",
+ "rollout_percentage": 100,
+ "aggregation_group_type_index": None,
+ "properties": [
+ {
+ "key": f"$survey_dismissed/{self.recurring_survey.id}/{iteration}",
+ "value": "is_not_set",
+ "operator": "is_not_set",
+ "type": "person",
+ },
+ {
+ "key": f"$survey_responded/{self.recurring_survey.id}/{iteration}",
+ "value": "is_not_set",
+ "operator": "is_not_set",
+ "type": "person",
+ },
+ ],
+ }
+ ],
+ "aggregation_group_type_index": None,
+ }
+
+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+ def test_flag_update_is_system_write_and_skips_approval_gate(self, _mock_enabled: MagicMock) -> None:
+ self.org.available_product_features = [{"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}]
+ self.org.save()
+ ApprovalPolicy.objects.create(
+ organization=self.org,
+ team=self.team,
+ action_key="feature_flag.update",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+ self.recurring_survey.start_date = now() - timedelta(self.iteration_frequency_days * 3)
+ self.recurring_survey.save()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ update_survey_iteration()
+
+ self.recurring_survey.refresh_from_db()
+ flag = self.recurring_survey.internal_targeting_flag
+ assert flag is not None
+ self.assertEqual(flag.filters, self._expected_iteration_filters(3))
+ self.assertFalse(ChangeRequest.objects.filter(team=self.team).exists())
+ log = ActivityLog.objects.get(scope="FeatureFlag", item_id=str(flag.id), activity="updated")
+ self.assertTrue(log.is_system)
+ self.assertIsNone(log.user)
+ self.assertEqual(flag.created_by, self.user)
+
+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+ def test_flag_create_is_system_write_and_skips_approval_gate(self, _mock_enabled: MagicMock) -> None:
+ self.org.available_product_features = [{"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}]
+ self.org.save()
+ ApprovalPolicy.objects.create(
+ organization=self.org,
+ team=self.team,
+ action_key="feature_flag.update",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+ self.recurring_survey.internal_targeting_flag = None
+ self.recurring_survey.start_date = now() - timedelta(self.iteration_frequency_days * 3)
+ self.recurring_survey.save()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ update_survey_iteration()
+
+ internal_flag = FeatureFlag.objects.get(key=self.recurring_survey.id)
+ # System write, but attribution is restored so the creator keeps flag access
+ self.assertEqual(internal_flag.created_by, self.user)
+ self.assertTrue(internal_flag.active)
+ self.assertEqual(internal_flag.filters, self._expected_iteration_filters(3))
+ self.assertFalse(ChangeRequest.objects.filter(team=self.team).exists())
+ log = ActivityLog.objects.get(scope="FeatureFlag", item_id=str(internal_flag.id), activity="created")
+ self.assertTrue(log.is_system)
+ self.assertIsNone(log.user)
diff --git a/posthog/tasks/update_survey_adaptive_sampling.py b/posthog/tasks/update_survey_adaptive_sampling.py
index 03b4b932b938..6ffae0498489 100644
--- a/posthog/tasks/update_survey_adaptive_sampling.py
+++ b/posthog/tasks/update_survey_adaptive_sampling.py
@@ -6,6 +6,8 @@ from django.utils.timezone import now
from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
+from products.feature_flags.backend.facade.api import update_flag
+from products.feature_flags.backend.facade.filters import set_first_release_condition_rollout
from products.surveys.backend.models import Survey
@@ -31,8 +33,18 @@ def _update_survey_adaptive_sampling(survey: Survey) -> None:
internal_response_sampling_flag = survey.internal_response_sampling_flag
# groups[0] is guaranteed to exist — survey flags are always created with groups in filters
# (see SurveySerializer._add_internal_response_sampling_filters)
- internal_response_sampling_flag.filters["groups"][0]["rollout_percentage"] = today_entry["rollout_percentage"]
- internal_response_sampling_flag.save(update_fields=["filters"])
+ update_flag(
+ internal_response_sampling_flag,
+ {
+ "filters": set_first_release_condition_rollout(
+ internal_response_sampling_flag.get_filters(), today_entry["rollout_percentage"]
+ )
+ },
+ team=survey.team,
+ # system write: skips the approval gate, because a beat task cannot
+ # surface an ApprovalRequired change request
+ user=None,
+ )
# this also doubles as a way to check that we're processing the final entry in the current sequence.
if today_entry["rollout_percentage"] == 100:
diff --git a/posthog/tasks/update_survey_iteration.py b/posthog/tasks/update_survey_iteration.py
index 602a1ae90bf7..663e499b65bb 100644
--- a/posthog/tasks/update_survey_iteration.py
+++ b/posthog/tasks/update_survey_iteration.py
@@ -1,10 +1,11 @@
from datetime import date, timedelta
-from typing import Any
from django.utils import timezone
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+from products.feature_flags.backend.facade.api import create_flag, update_flag
+from products.feature_flags.backend.facade.filters import replace_release_conditions
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.surveys.backend.models import Survey
@@ -68,47 +69,64 @@ def _has_final_iteration_ended(survey: Survey) -> bool:
return date.today() > final_iteration_end
-def _get_targeting_flag(survey: Survey) -> FeatureFlag | Any:
+def _get_targeting_flag(survey: Survey) -> FeatureFlag:
existing_targeting_flag: FeatureFlag | None = survey.internal_targeting_flag
- user_submitted_dismissed_filter = {
- "groups": [
- {
- "variant": "",
- "rollout_percentage": 100,
- "properties": [
- {
- "key": f"$survey_dismissed/{survey.id}/{survey.current_iteration}",
- "value": "is_not_set",
- "operator": "is_not_set",
- "type": "person",
- },
- {
- "key": f"$survey_responded/{survey.id}/{survey.current_iteration}",
- "value": "is_not_set",
- "operator": "is_not_set",
- "type": "person",
- },
- ],
- }
- ]
- }
+ user_submitted_dismissed_groups = [
+ {
+ "variant": "",
+ "rollout_percentage": 100,
+ "properties": [
+ {
+ "key": f"$survey_dismissed/{survey.id}/{survey.current_iteration}",
+ "value": "is_not_set",
+ "operator": "is_not_set",
+ "type": "person",
+ },
+ {
+ "key": f"$survey_responded/{survey.id}/{survey.current_iteration}",
+ "value": "is_not_set",
+ "operator": "is_not_set",
+ "type": "person",
+ },
+ ],
+ }
+ ]
if existing_targeting_flag is not None:
- # Note: new filters must come LAST to overwrite old iteration-unaware properties
- serialized_data_filters = {**existing_targeting_flag.filters, **user_submitted_dismissed_filter}
- existing_targeting_flag.filters = serialized_data_filters
- existing_targeting_flag.save()
- return existing_targeting_flag
- else:
- new_flag = FeatureFlag.objects.create(
+ # Note: groups are replaced wholesale so old iteration-unaware properties don't survive
+ return update_flag(
+ existing_targeting_flag,
+ {
+ "filters": replace_release_conditions(
+ existing_targeting_flag.get_filters(), user_submitted_dismissed_groups
+ )
+ },
team=survey.team,
- created_by=survey.created_by,
- active=True,
- key=str(survey.id),
- filters=user_submitted_dismissed_filter,
+ # system write: skips the approval gate, same as the create_flag call below
+ user=None,
)
- new_flag.save()
- return new_flag
+ # user=None: this is beat-task maintenance, so it must take the system-write
+ # path — a user-bearing write would engage the approval gate, and this task
+ # cannot surface an ApprovalRequired change request.
+ flag = create_flag(
+ {
+ "key": str(survey.id),
+ "active": True,
+ "filters": {"groups": user_submitted_dismissed_groups},
+ "creation_context": "surveys",
+ "_should_create_usage_dashboard": False,
+ },
+ team=survey.team,
+ user=None,
+ )
+ # The system write nulls created_by, which would cost the survey's creator their
+ # guaranteed access to the flag. Restore attribution with a raw column update:
+ # QuerySet.update() bypasses save()/signals, so the write stays system-attributed
+ # (is_system activity log, null last_modified_by) and cannot engage the gate.
+ if survey.created_by is not None:
+ FeatureFlag.objects.filter(pk=flag.pk).update(created_by=survey.created_by)
+ flag.created_by = survey.created_by
+ return flag
def _get_current_iteration(survey: Survey) -> int:
diff --git a/products/feature_flags/backend/facade/filters.py b/products/feature_flags/backend/facade/filters.py
index 3087eb38efb1..2e44311c0a6c 100644
--- a/products/feature_flags/backend/facade/filters.py
+++ b/products/feature_flags/backend/facade/filters.py
@@ -125,6 +125,28 @@ def replace_variant_distribution(current_filters: dict, variants: list[dict]) ->
return {**current_filters, "multivariate": {"variants": deepcopy(variants)}}
+def set_first_release_condition_rollout(current_filters: dict, rollout_percentage: int) -> dict:
+ """Set ``groups[0].rollout_percentage``, preserving everything else byte-for-byte.
+
+ Assumes at least one release group exists and raises (KeyError/IndexError) otherwise —
+ callers such as survey adaptive sampling only maintain flags they created with a
+ release condition in place, so a missing group is a broken invariant, not a case
+ to paper over.
+ """
+ new_filters = deepcopy(current_filters)
+ new_filters["groups"][0]["rollout_percentage"] = rollout_percentage
+ return new_filters
+
+
+def replace_release_conditions(current_filters: dict, groups: list[dict]) -> dict:
+ """Replace the release ``groups`` wholesale.
+
+ Every other key (``multivariate``, ``payloads``, aggregation, holdout/super groups)
+ is preserved — only who the flag releases to changes, not what it serves.
+ """
+ return {**current_filters, "groups": deepcopy(groups)}
+
+
def set_holdout(current_filters: dict, *, holdout_id: int | None, exclusion_percentage: float | None) -> dict:
"""Set (or clear) the flag-level ``holdout`` object on the filters.
diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.py
index e0768c259fa2..d06889bb7335 100644
--- a/products/feature_flags/backend/test/test_facade.py
+++ b/products/feature_flags/backend/test/test_facade.py
@@ -1,6 +1,7 @@
from copy import deepcopy
from typing import Any
+import pytest
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -25,8 +26,10 @@ from products.feature_flags.backend.facade.api import (
from products.feature_flags.backend.facade.filters import (
group_cohort_restriction_blocker,
groups_carry_restriction_marker,
+ replace_release_conditions,
replace_variant_distribution,
restrict_groups_to_cohort,
+ set_first_release_condition_rollout,
set_holdout,
strip_group_cohort_restriction,
)
@@ -443,6 +446,72 @@ class TestReplaceVariantDistribution:
assert current_filters["multivariate"]["variants"][0]["rollout_percentage"] == 100
+class TestReleaseConditionTransforms:
+ @parameterized.expand(
+ [
+ (
+ "survey_sampling_shape",
+ {"groups": [{"variant": "", "rollout_percentage": 100, "properties": []}]},
+ ),
+ (
+ "multi_group_with_multivariate_and_payloads",
+ {
+ "groups": [
+ {"variant": "", "rollout_percentage": 100, "properties": [{"key": "email", "type": "person"}]},
+ {"properties": [], "rollout_percentage": 50},
+ ],
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ "payloads": {"control": "{}"},
+ "aggregation_group_type_index": 1,
+ },
+ ),
+ ]
+ )
+ def test_set_first_release_condition_rollout_only_changes_first_group_rollout(self, _name, filters):
+ original = deepcopy(filters)
+
+ result = set_first_release_condition_rollout(filters, 20)
+
+ assert result["groups"][0]["rollout_percentage"] == 20
+ result["groups"][0]["rollout_percentage"] = original["groups"][0]["rollout_percentage"]
+ assert result == original
+ assert filters == original # input not mutated
+
+ @parameterized.expand(
+ [
+ ("missing_groups", {}, KeyError),
+ ("empty_groups", {"groups": []}, IndexError),
+ ]
+ )
+ def test_set_first_release_condition_rollout_raises_without_a_group(self, _name, filters, expected_error):
+ with pytest.raises(expected_error):
+ set_first_release_condition_rollout(filters, 20)
+
+ def test_replace_release_conditions_swaps_groups_and_preserves_the_rest(self):
+ filters: dict[str, Any] = {
+ "groups": [{"variant": "", "rollout_percentage": 100, "properties": [{"key": "old", "type": "person"}]}],
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ "payloads": {"control": "{}"},
+ "aggregation_group_type_index": 1,
+ }
+ new_groups: list[dict[str, Any]] = [
+ {"variant": "", "rollout_percentage": 100, "properties": [{"key": "new", "type": "person"}]}
+ ]
+
+ result = replace_release_conditions(filters, new_groups)
+
+ assert result == {
+ "groups": new_groups,
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ "payloads": {"control": "{}"},
+ "aggregation_group_type_index": 1,
+ }
+ assert result["groups"] is not new_groups
+ result["groups"][0]["properties"][0]["key"] = "mutated"
+ assert new_groups[0]["properties"][0]["key"] == "new"
+ assert filters["groups"][0]["properties"][0]["key"] == "old" # input not mutated
+
+
class TestExperimentRuleFromFilters:
@parameterized.expand(
[