: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
chore(api): keep evaluation context logic local in project.py (#63609)
Julian Bez2beec984af81
diff --git a/posthog/api/project.py b/posthog/api/project.pyindex e1e38f07fc21..fffb410c6cc0 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -42,8 +42,6 @@ from posthog.api.team import (_format_serializer_errors,get_or_mint_live_events_token,handle_conversations_token_on_update,- handle_default_evaluation_contexts,- handle_evaluation_context_suggestions,handle_logs_config,validate_team_attrs,)@@ -104,6 +102,11 @@ from posthog.user_permissions import UserPermissions, UserPermissionsSerializerMfrom posthog.utils import get_instance_realm, get_ip_address, get_week_start_for_country_codefrom products.feature_flags.backend.models import TeamFeatureFlagDefaultsConfig+from products.feature_flags.backend.models.evaluation_context import (+ EvaluationContext,+ TeamDefaultEvaluationContext,+ normalize_context_name,+)from products.notifications.backend.facade.api import (NotificationData,NotificationType,@@ -413,6 +416,143 @@ def team_event_ingestion_restrictions_view(team: Team, request: request.Request)return response.Response(data)+def team_default_evaluation_contexts_view(+ team: Team, request: request.Request, user_permissions: UserPermissions+) -> response.Response:+ """Manage default evaluation contexts for a project."""+ # Feature flags persist contexts under the project root team (RootTeamMixin), so scope+ # context lookups to the root team — otherwise flag-used contexts are invisible from+ # child environments.+ root_team = team.parent_team or team++ if request.method == "GET":+ defaults = TeamDefaultEvaluationContext.objects.filter(team=root_team).select_related("evaluation_context")+ defaults_data = [{"id": d.id, "name": d.evaluation_context.name} for d in defaults]+ all_contexts_qs = list(+ EvaluationContext.objects.filter(team=root_team)+ .values_list("name", "hidden_from_suggestions")+ .order_by("name")+ )+ all_contexts = [name for name, hidden in all_contexts_qs if not hidden]+ hidden_contexts = [name for name, hidden in all_contexts_qs if hidden]+ return response.Response(+ {+ "default_evaluation_contexts": defaults_data,+ "available_contexts": all_contexts,+ "hidden_contexts": hidden_contexts,+ "enabled": team.default_evaluation_contexts_enabled,+ }+ )++ elif request.method == "POST":+ context_name = request.data.get("context_name", "")+ if not isinstance(context_name, str):+ return response.Response({"error": "context_name must be a string"}, status=400)+ context_name = normalize_context_name(context_name)+ if not context_name:+ return response.Response({"error": "context_name is required"}, status=400)+ if len(context_name) > 255:+ return response.Response({"error": "context_name must be at most 255 characters"}, status=400)++ with transaction.atomic():+ existing = list(TeamDefaultEvaluationContext.objects.filter(team=root_team).select_for_update())+ if len(existing) >= 10:+ return response.Response({"error": "Maximum of 10 default evaluation contexts allowed"}, status=400)++ ctx, _ = EvaluationContext.objects.get_or_create(name=context_name, team=root_team)+ if ctx.hidden_from_suggestions:+ level = user_permissions.team(team).effective_membership_level+ if level is not None and level >= OrganizationMembership.Level.ADMIN:+ ctx.hidden_from_suggestions = False+ ctx.save(update_fields=["hidden_from_suggestions"])+ default_ctx, created = TeamDefaultEvaluationContext.objects.get_or_create(+ team=root_team, evaluation_context=ctx+ )++ if created:+ report_user_action(+ cast(User, request.user),+ "default evaluation context added",+ {"team_id": team.id, "context_name": context_name},+ team=team,+ request=request,+ )++ return response.Response(+ {+ "id": default_ctx.id,+ "name": ctx.name,+ "created": created,+ "hidden_from_suggestions": ctx.hidden_from_suggestions,+ }+ )++ else: # DELETE+ context_name = request.data.get("context_name", "") or request.GET.get("context_name", "")+ if not isinstance(context_name, str):+ return response.Response({"error": "context_name must be a string"}, status=400)+ context_name = normalize_context_name(context_name)+ if not context_name:+ return response.Response({"error": "context_name is required"}, status=400)++ with transaction.atomic():+ try:+ ctx = EvaluationContext.objects.get(name=context_name, team=root_team)+ deleted_count, _ = TeamDefaultEvaluationContext.objects.filter(+ team=root_team, evaluation_context=ctx+ ).delete()++ if deleted_count > 0:+ report_user_action(+ cast(User, request.user),+ "default evaluation context removed",+ {"team_id": team.id, "context_name": context_name},+ team=team,+ request=request,+ )++ return response.Response({"success": True})+ except EvaluationContext.DoesNotExist:+ return response.Response({"error": "Evaluation context not found"}, status=404)+++def team_evaluation_context_suggestions_view(team: Team, request: request.Request) -> response.Response:+ """Hide an evaluation context name from the flag editor's suggestion list, or restore it.++ POST hides the name; DELETE restores it. The underlying context row and any flags already+ using it are never modified — this only controls what gets suggested."""+ # Contexts are persisted under the project root team (see team_default_evaluation_contexts_view).+ root_team = team.parent_team or team++ context_name = request.data.get("context_name", "") or request.GET.get("context_name", "")+ if not isinstance(context_name, str):+ return response.Response({"error": "context_name must be a string"}, status=400)+ context_name = normalize_context_name(context_name)+ if not context_name:+ return response.Response({"error": "context_name is required"}, status=400)++ hidden = request.method == "POST"++ with transaction.atomic():+ try:+ ctx = EvaluationContext.objects.select_for_update().get(name=context_name, team=root_team)+ except EvaluationContext.DoesNotExist:+ return response.Response({"error": "Evaluation context not found"}, status=404)++ if ctx.hidden_from_suggestions != hidden:+ ctx.hidden_from_suggestions = hidden+ ctx.save(update_fields=["hidden_from_suggestions"])+ report_user_action(+ cast(User, request.user),+ "evaluation context suggestion hidden" if hidden else "evaluation context suggestion restored",+ {"team_id": team.id, "context_name": context_name},+ team=team,+ request=request,+ )++ return response.Response({"success": True, "name": context_name, "hidden_from_suggestions": hidden})++class ProjectSerializer(serializers.ModelSerializer):class Meta:model = Project@@ -1495,7 +1635,7 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets)def default_evaluation_contexts(self, request: request.Request, id: str, **kwargs) -> response.Response:"""Manage default evaluation contexts for a project."""- return handle_default_evaluation_contexts(request, self.get_object().passthrough_team, self.user_permissions)+ return team_default_evaluation_contexts_view(self.get_object().passthrough_team, request, self.user_permissions)@extend_schema(methods=["POST"],@@ -1528,7 +1668,7 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsetsPOST hides the name; DELETE restores it. The underlying context row and any flags alreadyusing it are never modified — this only controls what gets suggested."""- return handle_evaluation_context_suggestions(request, self.get_object().passthrough_team)+ return team_evaluation_context_suggestions_view(self.get_object().passthrough_team, request)@action(methods=["GET"], detail=True)def settings_as_of(self, request: request.Request, **kwargs) -> response.Response: