: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(flags): mirror evaluation context endpoints onto /api/projects/ (#63595)
Julian Bezcbb8ab0be79a
diff --git a/posthog/api/project.py b/posthog/api/project.pyindex d61a78ddf161..e1e38f07fc21 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -10,7 +10,8 @@ from django.utils import timezonefrom django.utils.dateparse import parse_datetimeimport structlog-from drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_view+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_viewfrom loginas.utils import is_impersonated_sessionfrom rest_framework import exceptions, filters, request, response, serializers, viewsetsfrom rest_framework.decorators import action@@ -29,6 +30,8 @@ from posthog.api.team import (PROMOTED_PRODUCT_INTENT_DESCRIPTION,TEAM_CONFIG_FIELDS,TEAM_CONFIG_MEMBER_FIELDS_SET,+ EvaluationContextSuggestionRequestSerializer,+ EvaluationContextSuggestionResponseSerializer,PromotedProductIntentSerializer,TeamCustomerAnalyticsConfigSerializer,TeamMarketingAnalyticsConfigSerializer,@@ -39,6 +42,8 @@ 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,)@@ -99,11 +104,6 @@ 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,@@ -344,78 +344,6 @@ def team_experiments_config_view(team: Team, request: request.Request) -> responreturn response.Response(TeamExperimentsConfigSerializer(config).data)-def team_default_evaluation_contexts_view(team: Team, request: request.Request) -> response.Response:- """Manage default evaluation contexts for a project."""- if request.method == "GET":- defaults = TeamDefaultEvaluationContext.objects.filter(team=team).select_related("evaluation_context")- defaults_data = [{"id": d.id, "name": d.evaluation_context.name} for d in defaults]- all_contexts = list(EvaluationContext.objects.filter(team=team).values_list("name", flat=True).order_by("name"))- return response.Response(- {- "default_evaluation_contexts": defaults_data,- "available_contexts": all_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=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=team)- default_ctx, created = TeamDefaultEvaluationContext.objects.get_or_create(team=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})-- 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=team)- deleted_count, _ = TeamDefaultEvaluationContext.objects.filter(- team=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_settings_as_of_view(team: Team, request: request.Request) -> response.Response:"""Return the project settings as of the provided timestamp.@@ -1567,7 +1495,40 @@ 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 team_default_evaluation_contexts_view(self.get_object().passthrough_team, request)+ return handle_default_evaluation_contexts(request, self.get_object().passthrough_team, self.user_permissions)++ @extend_schema(+ methods=["POST"],+ request=EvaluationContextSuggestionRequestSerializer,+ responses={200: EvaluationContextSuggestionResponseSerializer},+ extensions={"x-product": "feature_flags"},+ )+ @extend_schema(+ methods=["DELETE"],+ parameters=[+ OpenApiParameter(+ name="context_name",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=True,+ description="Name of the evaluation context to restore to suggestions.",+ )+ ],+ responses={200: EvaluationContextSuggestionResponseSerializer},+ extensions={"x-product": "feature_flags"},+ )+ @action(+ methods=["POST", "DELETE"],+ detail=True,+ permission_classes=[TeamMemberStrictManagementPermission],+ )+ def evaluation_context_suggestions(self, request: request.Request, id: str, **kwargs) -> 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.+ """+ return handle_evaluation_context_suggestions(request, self.get_object().passthrough_team)@action(methods=["GET"], detail=True)def settings_as_of(self, request: request.Request, **kwargs) -> response.Response:diff --git a/posthog/api/team.py b/posthog/api/team.pyindex c269af9878d7..90319cb7e98d 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -135,6 +135,147 @@ def handle_logs_config(request: request.Request, team: Team) -> response.Responsreturn response.Response(TeamLogsConfigSerializer(config).data)+def handle_default_evaluation_contexts(+ request: request.Request, team: Team, user_permissions: UserPermissions+) -> response.Response:+ """Shared handler for the default_evaluation_contexts action — exposed under both the+ team/environment and project routers so /api/projects/ and /api/environments/ cannot drift apart.+ Manage default evaluation contexts for a team."""+ # 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 handle_evaluation_context_suggestions(request: request.Request, team: Team) -> response.Response:+ """Shared handler for the evaluation_context_suggestions action — exposed under both the+ team/environment and project routers so /api/projects/ and /api/environments/ cannot drift apart.++ 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 default_evaluation_contexts).+ 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})++def _format_serializer_errors(serializer_errors: dict) -> str:"""Formats DRF serializer errors into a human readable string."""error_messages: list[str] = []@@ -1931,101 +2072,7 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo)def default_evaluation_contexts(self, request: request.Request, id: str, **kwargs) -> response.Response:"""Manage default evaluation contexts for a team."""- team = self.get_object()- # 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 = self.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)+ return handle_default_evaluation_contexts(request, self.get_object(), self.user_permissions)@extend_schema(methods=["POST"],@@ -2058,37 +2105,7 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.MoPOST hides the name; DELETE restores it. The underlying context row and any flags alreadyusing it are never modified — this only controls what gets suggested."""- team = self.get_object()- # Contexts are persisted under the project root team (see default_evaluation_contexts).- 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})+ return handle_evaluation_context_suggestions(request, self.get_object())@action(methods=["GET"],diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex ffbda077a08e..9e1c561fe344 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -1339,6 +1339,13 @@ export interface PatchedScheduledChangeApi {readonly timezone?: string | null}+export type OrganizationsProjectsEvaluationContextSuggestionsDestroyParams = {+ /**+ * Name of the evaluation context to restore to suggestions.+ */+ context_name: string+}+export type EnvironmentsEvaluationContextSuggestionsDestroyParams = {/*** Name of the evaluation context to restore to suggestions.diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.tsindex dd18656d7af7..07c4b0863745 100644--- a/products/feature_flags/frontend/generated/api.ts+++ b/products/feature_flags/frontend/generated/api.ts@@ -36,6 +36,7 @@ import type {FlagValueResponseApi,FlagValueValuesRetrieveParams,MyFlagsResponseApi,+ OrganizationsProjectsEvaluationContextSuggestionsDestroyParams,PaginatedFeatureFlagListApi,PaginatedScheduledChangeListApi,PatchedFeatureFlagPartialUpdateRequestSchemaApi,@@ -95,6 +96,74 @@ export const featureFlagsCopyFlagsCreate = async (})}+export const getOrganizationsProjectsEvaluationContextSuggestionsCreateUrl = (organizationId: string, id: number) => {+ return `/api/organizations/${organizationId}/projects/${id}/evaluation_context_suggestions/`+}++/**+ * 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.+ */+export const organizationsProjectsEvaluationContextSuggestionsCreate = async (+ organizationId: string,+ id: number,+ evaluationContextSuggestionRequestApi: EvaluationContextSuggestionRequestApi,+ options?: RequestInit+): Promise<EvaluationContextSuggestionResponseApi> => {+ return apiMutator<EvaluationContextSuggestionResponseApi>(+ getOrganizationsProjectsEvaluationContextSuggestionsCreateUrl(organizationId, id),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(evaluationContextSuggestionRequestApi),+ }+ )+}++export const getOrganizationsProjectsEvaluationContextSuggestionsDestroyUrl = (+ organizationId: string,+ id: number,+ params: OrganizationsProjectsEvaluationContextSuggestionsDestroyParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/organizations/${organizationId}/projects/${id}/evaluation_context_suggestions/?${stringifiedParams}`+ : `/api/organizations/${organizationId}/projects/${id}/evaluation_context_suggestions/`+}++/**+ * 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.+ */+export const organizationsProjectsEvaluationContextSuggestionsDestroy = async (+ organizationId: string,+ id: number,+ params: OrganizationsProjectsEvaluationContextSuggestionsDestroyParams,+ options?: RequestInit+): Promise<EvaluationContextSuggestionResponseApi> => {+ return apiMutator<EvaluationContextSuggestionResponseApi>(+ getOrganizationsProjectsEvaluationContextSuggestionsDestroyUrl(organizationId, id, params),+ {+ ...options,+ method: 'DELETE',+ }+ )+}+export const getEnvironmentsEvaluationContextSuggestionsCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/environments/${id}/evaluation_context_suggestions/`}diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex 50801e2eeb3b..8c377e671176 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -33,6 +33,23 @@ export const FeatureFlagsCopyFlagsCreateBody = /* @__PURE__ */ zod.object({),})+/**+ * 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.+ */+export const organizationsProjectsEvaluationContextSuggestionsCreateBodyContextNameMax = 255++export const OrganizationsProjectsEvaluationContextSuggestionsCreateBody = /* @__PURE__ */ zod.object({+ context_name: zod+ .string()+ .max(organizationsProjectsEvaluationContextSuggestionsCreateBodyContextNameMax)+ .describe(+ "Name of the evaluation context to hide from (POST) or restore to (DELETE) the flag editor's suggestion list. Case-insensitive and whitespace-trimmed."+ ),+})+/*** Hide an evaluation context name from the flag editor's suggestion list, or restore it.*diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 6cde8fd8885b..3c1c18531232 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -318,6 +318,12 @@ tools:org-feature-flags-retrieve:operation: org_feature_flags_retrieveenabled: false+ organizations-projects-evaluation-context-suggestions-create:+ operation: organizations_projects_evaluation_context_suggestions_create+ enabled: false+ organizations-projects-evaluation-context-suggestions-destroy:+ operation: organizations_projects_evaluation_context_suggestions_destroy+ enabled: falsescheduled-changes-create:operation: scheduled_changes_createenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 49618a732d76..7f01eefe0cdd 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -48915,6 +48915,13 @@ export namespace Schemas {search?: string;};+ export type OrganizationsProjectsEvaluationContextSuggestionsDestroyParams = {+ /**+ * Name of the evaluation context to restore to suggestions.+ */+ context_name: string;+ };+export type RoleExternalReferencesListParams = {/*** Number of results to return per page.