: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(subscriptions): evaluate AI subscription create gate per-user (#62385)
Vasco de Krijgere48d42b5bede
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 294a146b7579..6625ff3eadd6 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -86,19 +86,21 @@ def _invalidate_summary_quota_cache(organization_id) -> None:cache.delete(_summary_quota_cache_key(organization_id))-def _ai_create_gate_reason(organization) -> Optional[str]:+def _ai_create_gate_reason(organization, distinct_id: str) -> Optional[str]:if not settings.DEBUG and not is_cloud():return "AI subscriptions are only available in PostHog Cloud."if not organization.is_ai_data_processing_approved:return "Your organization must approve AI data processing before creating AI subscriptions."+ # Per-user gate so people can self-enable via feature previews (early access) — the flag is+ # person-based. AI credits and the subscription limit stay org-scoped, enforced separately.+ # Non-user callers get a synthetic team_<id> distinct_id that never matches → fails closed.if not posthoganalytics.feature_enabled(SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY,- str(organization.id),- groups={"organization": str(organization.id)},+ distinct_id,only_evaluate_locally=False,send_feature_flag_events=False,):- return "AI subscriptions are not enabled for your organization."+ return "AI subscriptions are not enabled for your account."return None@@ -286,7 +288,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):raise ValidationError({"target_type": ["AI subscriptions only support email or slack delivery."]})# Gates fire on create only; existing AI subs stay editable.if existing is None:- gate_reason = _ai_create_gate_reason(self.context["get_organization"]())+ gate_reason = _ai_create_gate_reason(self.context["get_organization"](), self._caller_distinct_id())if gate_reason is not None:raise ValidationError(gate_reason)@@ -514,6 +516,8 @@ class SubscriptionSerializer(serializers.ModelSerializer):Scoped by organization (not user) so gates are stable across a team'smembers. `only_evaluate_locally=False` so we respect server-side cohort/ property conditions — these checks aren't on a hot path.+ (`_ai_create_gate_reason` is intentionally person-scoped instead — it+ backs a per-user early-access opt-in — so don't unify the two.)"""request = self.context.get("request")if not request or not getattr(request, "user", None) or not getattr(request.user, "distinct_id", None):diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 2ba4cb555649..76b7df03439a 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -12,7 +12,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom temporalio.exceptions import WorkflowAlreadyStartedError-from posthog.constants import AvailableFeature+from posthog.constants import SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY, AvailableFeaturefrom posthog.models import Teamfrom posthog.models.filters.filter import Filterfrom posthog.models.integration import Integration@@ -2388,6 +2388,23 @@ class TestAISubscriptionAPI(APILicensedTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "AI data processing" in str(response.json())+ def test_create_gate_evaluates_flag_per_user_without_org_group(self, mock_is_cloud, mock_flag, mock_sync):+ # Early-access gate is person-based so users self-enable via feature previews — the flag+ # must be evaluated for the requesting user's distinct_id, never overridden to the org group.+ self._enable_ai()+ self._mock_temporal(mock_sync)+ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(),+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ gate_calls = [+ c for c in mock_flag.call_args_list if c.args and c.args[0] == SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY+ ]+ assert gate_calls, "ai-subscriptions flag was never evaluated on create"+ assert gate_calls[-1].args[1] == str(self.user.distinct_id)+ assert gate_calls[-1].kwargs.get("groups") is None+def test_rejects_when_not_cloud_or_debug(self, mock_is_cloud, mock_flag, mock_sync):self._enable_ai()mock_is_cloud.return_value = False@@ -2409,7 +2426,7 @@ class TestAISubscriptionAPI(APILicensedTest):self._make_ai_payload(),)assert response.status_code == status.HTTP_400_BAD_REQUEST- assert "not enabled" in str(response.json())+ assert "not enabled for your account" in str(response.json())@parameterized.expand([