: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
fix(marketing-analytics): evaluate the Setup flag for the requesting person (#83409)
Javier Bahamondes1b71291565ff
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.pyindex 4fc68f401692..d2604709e659 100644--- a/products/marketing_analytics/backend/api.py+++ b/products/marketing_analytics/backend/api.py@@ -75,23 +75,33 @@ from products.warehouse_sources.backend.facade.models import DataWarehouseTablelogger = structlog.get_logger(__name__)-def _setup_enabled(team: Team) -> bool:- """Evaluate the Setup flag once per team instance.-- Grouped on organization, matching how every other marketing-analytics flag is- evaluated, so a team can't disagree with its org. Cached on the instance because a- second call in the same request would fire a redundant `$feature_flag_called`.+def _setup_enabled(request: Request, team: Team) -> bool:+ """Evaluate the Setup flag once per request.++ Evaluated for the requesting person, because the flag's release conditions target+ people and the frontend renders the Setup tab off that same per-person answer.+ Evaluating it against anything else is how the tab ends up sitting on top of an+ endpoint that 404s. The organization group still goes along, so a group release+ condition matches too. Cached on the request because a second call in the same one+ would fire a redundant `$feature_flag_called`."""- cached = getattr(team, "_ma_setup_flag", None)+ cached = getattr(request, "_ma_setup_flag", None)if cached is not None:return cached+ person_properties = {}+ email = getattr(request.user, "email", None)+ if email:+ person_properties["email"] = emailenabled = feature_enabled_or_false("marketing-analytics-setup",- str(team.uuid),+ # Service credentials authenticate as a synthetic user with no person behind them;+ # the team UUID keeps the call well-formed, and a person condition won't match it.+ getattr(request.user, "distinct_id", None) or str(team.uuid),groups={"organization": str(team.organization.id)},+ person_properties=person_properties,group_properties={"organization": {"id": str(team.organization.id)}},)- team._ma_setup_flag = enabled # type: ignore[attr-defined]+ request._ma_setup_flag = enabled # type: ignore[attr-defined]return enabled@@ -1457,7 +1467,7 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):@action(methods=["GET"], detail=False, url_path="setup_plan", required_scopes=["marketing_analytics:read"])def setup_plan(self, request: Request, *args, **kwargs) -> Response:# 404 rather than 403: an unreleased endpoint should look absent, not forbidden.- if not _setup_enabled(self.team):+ if not _setup_enabled(request, self.team):raise NotFound("Marketing analytics setup is not enabled for this project.")date_from = request.validated_query_data["date_from"]@@ -1513,7 +1523,7 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):def apply_setup_ops(self, request: Request, *args, **kwargs) -> Response:# Same gate as setup_plan: the ops only come from a plan, so an unreleased# read side means there is nothing legitimate to apply.- if not _setup_enabled(self.team):+ if not _setup_enabled(request, self.team):raise NotFound("Marketing analytics setup is not enabled for this project.")# Every op here writes a field the team PATCH puts in TEAM_CONFIG_ADMIN_FIELDS_SET,diff --git a/products/marketing_analytics/backend/test_api_setup_plan.py b/products/marketing_analytics/backend/test_api_setup_plan.pyindex 2603adc29bca..be26687cd49d 100644--- a/products/marketing_analytics/backend/test_api_setup_plan.py+++ b/products/marketing_analytics/backend/test_api_setup_plan.py@@ -164,12 +164,19 @@ class TestSetupPlanFeatureFlag(APIBaseTest):assert flag.call_count == 1- def test_the_flag_is_grouped_on_the_organization(self):- # Every other marketing-analytics flag is org-grouped; a team-only evaluation- # here would let one project disagree with the rest of its org.+ def test_the_flag_is_evaluated_for_the_requesting_person(self):+ # The flag targets people, and the frontend renders the Setup tab off that same+ # per-person answer. Evaluating it against the team instead answers for nobody, so+ # the tab lands on an endpoint that 404s. Two people to also catch an answer+ # cached somewhere that outlives one request.+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+with patch(_FLAG_TARGET, return_value=True) as flag, patch(_PLAN_TARGET, return_value=_plan()):self.client.get(self.url)+ self.client.force_login(other_user)+ self.client.get(self.url)+ assert [call.args[1] for call in flag.call_args_list] == [self.user.distinct_id, other_user.distinct_id]assert flag.call_args.kwargs["groups"] == {"organization": str(self.team.organization.id)}