: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
feat(flags): allow staff to override the per-team flag limit (#81020)
Phil Haackc993c28bc2ba
diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex ec84c07a93e6..990e94d0d44c 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -112,7 +112,9 @@ TEAM_METADATA_CACHE_VERIFICATION_GRACE_PERIOD_MINUTES: int = get_from_env(# Defaults are set well above observed production maximums to avoid impacting# normal usage while protecting against extreme outliers.-# Maximum number of feature flags allowed per team+# Maximum number of feature flags allowed per team. This is the fleet-wide default: staff can+# raise or lower it for a single team via TeamFeatureFlagsConfig.max_feature_flags_override.+# MAX_FEATURE_FLAG_FILTER_SIZE_BYTES below has no per-team override.MAX_FEATURE_FLAGS_PER_TEAM: int = get_from_env("MAX_FEATURE_FLAGS_PER_TEAM", 2000, type_cast=int)# Maximum size in bytes for a single flag's filters JSONdiff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 93c722e7fb71..5ff814fd89a1 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -92,6 +92,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import (get_decrypted_flag_payloads_protected,)from products.feature_flags.backend.flag_analytics import increment_request_count+from products.feature_flags.backend.flag_limits import get_max_feature_flags_for_teamfrom products.feature_flags.backend.flag_status import (FeatureFlagStatusChecker,exclude_archived_unless_requested,@@ -590,7 +591,7 @@ def check_flag_limits_for_team(if not is_create:return- count_limit = settings.MAX_FEATURE_FLAGS_PER_TEAM+ count_limit = get_max_feature_flags_for_team(team_id)flag_count = FeatureFlag.objects.filter(team_id=team_id).count()if flag_count >= count_limit:diff --git a/products/feature_flags/backend/api/staff_team_config.py b/products/feature_flags/backend/api/staff_team_config.pyindex 2ba089a622e3..5c81490ea32c 100644--- a/products/feature_flags/backend/api/staff_team_config.py+++ b/products/feature_flags/backend/api/staff_team_config.py@@ -1,8 +1,13 @@+from typing import Any++from django.db.models import Count+import structlogfrom drf_spectacular.utils import OpenApiResponse, extend_schema_serializerfrom rest_framework import request, response, serializers, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound+from rest_framework.parsers import JSONParserfrom rest_framework.permissions import IsAuthenticatedfrom posthog.api.mixins import validated_request@@ -12,7 +17,15 @@ from posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.permissions import IsStaffUserfrom products.feature_flags.backend.api.staff_cache import _team_ids_field-from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig+from products.feature_flags.backend.flag_limits import (+ get_max_feature_flags_override_for_team,+ resolve_max_feature_flags,+)+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.team_feature_flags_config import (+ MAX_FEATURE_FLAGS_OVERRIDE_CEILING,+ TeamFeatureFlagsConfig,+)logger = structlog.get_logger(__name__)@@ -21,6 +34,25 @@ logger = structlog.get_logger(__name__)# value today by coincidence, not by requirement.MAX_TEAM_IDS_PER_QUERY = 50+MUTABLE_SETTINGS = ("minimal_flag_called_events", "max_feature_flags_override")+++def _config_row(+ *,+ team_id: int,+ minimal_flag_called_events: bool,+ max_feature_flags_override: int | None,+ feature_flag_count: int,+) -> dict[str, Any]:+ """Build the row shape shared by list() and set(), which both feed the same staff tools table."""+ return {+ "team_id": team_id,+ "minimal_flag_called_events": minimal_flag_called_events,+ "max_feature_flags_override": max_feature_flags_override,+ "effective_max_feature_flags": resolve_max_feature_flags(max_feature_flags_override),+ "feature_flag_count": feature_flag_count,+ }+class StaffTeamConfigQuerySerializer(serializers.Serializer):team_ids = _team_ids_field(@@ -38,6 +70,25 @@ class StaffTeamConfigSerializer(serializers.Serializer):"(omitting fields only needed for experiments) instead of the full legacy shape."))+ max_feature_flags_override = serializers.IntegerField(+ allow_null=True,+ help_text=(+ "Per-team override for the maximum number of feature flags this team may create, "+ "or null when the team uses the global default."+ ),+ )+ effective_max_feature_flags = serializers.IntegerField(+ help_text=(+ "The flag-count limit actually enforced for this team: the override when one is set, "+ "otherwise the global MAX_FEATURE_FLAGS_PER_TEAM setting."+ )+ )+ feature_flag_count = serializers.IntegerField(+ help_text=(+ "Number of feature flags the team has today, excluding soft-deleted ones, counted the "+ "same way the limit is enforced."+ )+ )@extend_schema_serializer(many=False)@@ -48,21 +99,43 @@ class StaffTeamConfigListResponseSerializer(serializers.Serializer):class StaffTeamConfigMutationSerializer(serializers.Serializer):team_id = serializers.IntegerField(help_text="Team id to update. Exactly one team per request.")minimal_flag_called_events = serializers.BooleanField(+ required=False,help_text=(- "New value for the team's minimal_flag_called_events setting. Only set true after "- "confirming that team's SDK versions support the slim $feature_flag_called event shape."- )+ "New value for the team's minimal_flag_called_events setting. Omit to leave it "+ "unchanged. Only set true after confirming that team's SDK versions support the slim "+ "$feature_flag_called event shape."+ ),+ )+ max_feature_flags_override = serializers.IntegerField(+ required=False,+ allow_null=True,+ min_value=1,+ max_value=MAX_FEATURE_FLAGS_OVERRIDE_CEILING,+ help_text=(+ f"New per-team flag-count limit (1-{MAX_FEATURE_FLAGS_OVERRIDE_CEILING:,}). Send null "+ "to clear the override so the team falls back to the global default. Omit to leave it "+ "unchanged."+ ),)+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ if not attrs.keys() & MUTABLE_SETTINGS:+ raise serializers.ValidationError("Provide at least one setting to update.")+ return attrs+class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):"""- Staff-only, unscoped read/write for TeamFeatureFlagsConfig (currently just- minimal_flag_called_events).+ Staff-only, unscoped read/write for TeamFeatureFlagsConfig: the minimal_flag_called_events+ rollout gate and the per-team feature-flag count override.++ Single-team writes only, by design. minimal_flag_called_events is flipped one team at a time+ after staff verify that team's SDK versions support the slim $feature_flag_called event shape,+ and max_feature_flags_override is a per-customer capacity grant. Neither is a bulk operation,+ unlike the cache tools' rebuild and clear.- Single-team writes only, by design: this setting is meant to be flipped one team at a time- after staff manually verify that team's SDK versions support the slim $feature_flag_called- event shape, unlike the cache tools' bulk rebuild/clear.+ set() takes partial updates: omit a setting to leave it unchanged, and send+ max_feature_flags_override as null to clear the override.Registered on the root router so it is not team-nested; staff act on teams they do notbelong to, same as staff_cache.py / staff_teams.py.@@ -73,6 +146,11 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):# surface (see posthog/api/documentation.py's INTERNAL handling).scope_object = "INTERNAL"permission_classes = [IsAuthenticated, IsStaffUser]+ # set() distinguishes an absent setting from one sent explicitly, and DRF's BooleanField+ # materializes an absent field as False for form-encoded bodies (see default_empty_html in+ # rest_framework/fields.py). Under FormParser a request meaning to set only the flag limit+ # would therefore also switch minimal_flag_called_events off, so restrict this to JSON.+ parser_classes = [JSONParser]@validated_request(query_serializer=StaffTeamConfigQuerySerializer,@@ -82,17 +160,50 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):# Dedupe (preserving order) so a caller passing the same id twice doesn't get duplicate# rows in `results`, matching staff_cache.py's handling of team_ids.team_ids: list[int] = list(dict.fromkeys(request.validated_query_data["team_ids"]))- existing_team_ids = set(Team.objects.filter(id__in=team_ids).values_list("id", flat=True))- config_by_team_id = dict(- TeamFeatureFlagsConfig.objects.filter(team_id__in=team_ids).values_list(- "team_id", "minimal_flag_called_events"+ # Each team maps to its project root. The override and the flag count are both+ # project-scoped: check_flag_limits_for_team reads the override off the root+ # (get_max_feature_flags_override_for_team) and counts through FeatureFlag.objects, whose+ # RootTeamManager rewrites team_id= to the root. Reading either off the environment team+ # would show a limit the validator does not enforce.+ root_team_id_by_team_id = {+ team_id: parent_team_id or team_id+ for team_id, parent_team_id in Team.objects.filter(id__in=team_ids).values_list("id", "parent_team_id")+ }+ root_team_ids = set(root_team_id_by_team_id.values())+ # minimal_flag_called_events stays per-team (the Rust and nodejs readers key on the+ # literal team), so it is read from each team's own row; the override is read from the root.+ config_by_team_id = TeamFeatureFlagsConfig.objects.in_bulk(team_ids)+ override_by_root_team_id = dict(+ TeamFeatureFlagsConfig.objects.filter(team_id__in=root_team_ids).values_list(+ "team_id", "max_feature_flags_override"))- results = [- {"team_id": team_id, "minimal_flag_called_events": config_by_team_id.get(team_id, False)}- for team_id in team_ids- if team_id in existing_team_ids- ]+ # FeatureFlag.objects excludes soft-deleted rows, so counting the root team gives the+ # number check_flag_limits_for_team compares against the limit. Staff reading this number+ # next to the limit have to see the number the validator sees.+ flag_count_by_root_team_id = dict(+ FeatureFlag.objects.filter(team_id__in=root_team_ids)+ .values("team_id")+ .annotate(count=Count("id"))+ .values_list("team_id", "count")+ )++ results = []+ for team_id in team_ids:+ if team_id not in root_team_id_by_team_id:+ continue+ root_team_id = root_team_id_by_team_id[team_id]+ # An unsaved instance stands in for a legacy team whose row predates this extension,+ # so the model's own field defaults answer for it rather than a second copy here.+ config = config_by_team_id.get(team_id) or TeamFeatureFlagsConfig()+ results.append(+ _config_row(+ team_id=team_id,+ minimal_flag_called_events=config.minimal_flag_called_events,+ max_feature_flags_override=override_by_root_team_id.get(root_team_id),+ feature_flag_count=flag_count_by_root_team_id.get(root_team_id, 0),+ )+ )return response.Response({"results": results})@validated_request(@@ -101,39 +212,81 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):)@action(methods=["POST"], detail=False)def set(self, request: request.Request, **kwargs) -> response.Response:- team_id: int = request.validated_data["team_id"]- new_value: bool = request.validated_data["minimal_flag_called_events"]+ validated = request.validated_data+ team_id: int = validated["team_id"]team = Team.objects.filter(id=team_id).first()if team is None:raise NotFound(f"Team {team_id} not found.")+ # The limit is enforced against the project's whole flag set, and get_max_feature_flags_for_team+ # reads the override off the project root, so a row written here would never be read.+ # minimal_flag_called_events stays per-team (the Rust and nodejs readers key on the literal+ # team), which is why only the override is refused rather than the whole request.+ if "max_feature_flags_override" in validated and team.parent_team_id is not None:+ raise serializers.ValidationError(+ f"Team {team_id} is an environment of project {team.parent_team_id}. Set the flag limit on "+ f"team {team.parent_team_id}: it is enforced against the whole project's flags."+ )+config = get_or_create_team_extension(team, TeamFeatureFlagsConfig)- old_value = config.minimal_flag_called_events- config.minimal_flag_called_events = new_value- config.save(update_fields=["minimal_flag_called_events"])+ old_minimal_flag_called_events = config.minimal_flag_called_events+ old_max_feature_flags_override = config.max_feature_flags_override++ # Saving only the fields actually sent keeps two staff editing different settings on the+ # same team from overwriting each other.+ update_fields = [setting for setting in MUTABLE_SETTINGS if setting in validated]+ for setting in update_fields:+ setattr(config, setting, validated[setting])+ config.save(update_fields=update_fields)- # posthog.tasks.team_metadata sits under posthog.tasks, whose __init__ is a celery- # autoimport aggregator that pulls in every task module — keep that off the API- # router's import path by deferring it to call time. The local tasks module is- # deferred for the same reason (it imports celery machinery).- from posthog.tasks.team_metadata import update_team_metadata_cache_task # noqa: PLC0415+ if "minimal_flag_called_events" in validated:+ # posthog.tasks.team_metadata sits under posthog.tasks, whose __init__ is a celery+ # autoimport aggregator that pulls in every task module — keep that off the API+ # router's import path by deferring it to call time. The local tasks module is+ # deferred for the same reason (it imports celery machinery).+ from posthog.tasks.team_metadata import update_team_metadata_cache_task # noqa: PLC0415- from products.feature_flags.backend.tasks import update_team_flags_cache # noqa: PLC0415+ from products.feature_flags.backend.tasks import update_team_flags_cache # noqa: PLC0415- # /flags and /decide read this value out of team_metadata_hypercache, and local-eval- # SDKs read it out of the flag-definitions blob — neither reads the DB, so the write- # above has no effect until both caches are rebuilt.- update_team_metadata_cache_task.delay(team.id)- update_team_flags_cache.delay(team.id)+ # /flags and /decide read this value out of team_metadata_hypercache, and local-eval+ # SDKs read it out of the flag-definitions blob, so the write above has no effect+ # until both caches are rebuilt. Re-sending an unchanged value rebuilds them anyway,+ # which is the way back from a failed cache write.+ update_team_metadata_cache_task.delay(team.id)+ update_team_flags_cache.delay(team.id)++ # old_value/new_value stay bound to minimal_flag_called_events under those names because+ # dashboards outside this repo were built on them before the endpoint took a second setting.+ changed_values: dict[str, Any] = {}+ if "minimal_flag_called_events" in validated:+ changed_values["old_value"] = old_minimal_flag_called_events+ changed_values["new_value"] = config.minimal_flag_called_events+ if "max_feature_flags_override" in validated:+ changed_values["old_max_feature_flags_override"] = old_max_feature_flags_override+ changed_values["new_max_feature_flags_override"] = config.max_feature_flags_overridelogger.info("flags_staff_team_config_updated",staff_user_id=request.user.id,was_impersonated=is_impersonated(request),team_id=team.id,- old_value=old_value,- new_value=new_value,+ updated_fields=update_fields,+ **changed_values,)- return response.Response({"team_id": team.id, "minimal_flag_called_events": new_value})+ # The row has to show the root's override, matching list() and the validator. A root team's+ # own config is already that, and an environment team reaches here only on a+ # minimal_flag_called_events-only edit, since the override write is refused above.+ return response.Response(+ _config_row(+ team_id=team.id,+ minimal_flag_called_events=config.minimal_flag_called_events,+ max_feature_flags_override=(+ config.max_feature_flags_override+ if team.parent_team_id is None+ else get_max_feature_flags_override_for_team(team.parent_team_id)+ ),+ feature_flag_count=FeatureFlag.objects.filter(team_id=team.id).count(),+ )+ )diff --git a/products/feature_flags/backend/api/staff_teams.py b/products/feature_flags/backend/api/staff_teams.pyindex 260ebfa9557a..86d14d6b57ee 100644--- a/products/feature_flags/backend/api/staff_teams.py+++ b/products/feature_flags/backend/api/staff_teams.py@@ -51,6 +51,13 @@ class StaffTeamResultSerializer(serializers.Serializer):organization_id = serializers.CharField(help_text="Organization uuid that owns the team.")organization_name = serializers.CharField(help_text="Organization name that owns the team.")project_id = serializers.IntegerField(help_text="Project id the team belongs to.")+ parent_team_id = serializers.IntegerField(+ allow_null=True,+ help_text=(+ "Project root team id when this team is an environment, or null when it is the root. "+ "The flag limit is set on the root, so a team with this set cannot take an override."+ ),+ )@extend_schema_serializer(many=False)@@ -101,7 +108,9 @@ class FeatureFlagsStaffTeamSearchViewSet(viewsets.ViewSet):Team.objects.filter(query).annotate(organization_name=F("organization__name")).order_by("id")- .values("id", "name", "api_token", "organization_id", "organization_name", "project_id")[:limit]+ .values("id", "name", "api_token", "organization_id", "organization_name", "project_id", "parent_team_id")[+ :limit+ ])return response.Response(StaffTeamSearchResponseSerializer({"results": list(teams)}).data)diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex db9984d6581e..72972ad6a034 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -237,6 +237,24 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.13+ '''+ SELECT "posthog_team"."parent_team_id" AS "parent_team_id"+ FROM "posthog_team"+ WHERE "posthog_team"."id" = 99999+ ORDER BY "posthog_team"."id" ASC+ LIMIT 1+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.14+ '''+ SELECT "feature_flags_teamfeatureflagsconfig"."max_feature_flags_override" AS "max_feature_flags_override"+ FROM "feature_flags_teamfeatureflagsconfig"+ WHERE "feature_flags_teamfeatureflagsconfig"."team_id" = 99999+ ORDER BY "feature_flags_teamfeatureflagsconfig"."team_id" ASC+ LIMIT 1+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.15'''SELECT COUNT(*) AS "__count"FROM "posthog_featureflag"@@ -251,7 +269,7 @@AND "posthog_featureflag"."team_id" = 99999)))'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.14+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.16'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -354,7 +372,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.15+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.17'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -398,7 +416,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.16+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.18'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",@@ -428,7 +446,7 @@AND "posthog_team"."project_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.17+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.19'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -530,50 +548,6 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.18- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."surface",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE (("posthog_filesystem"."surface" IS NULL- OR "posthog_filesystem"."surface" = 'web')- AND "posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'feature_flag'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.19- '''- SELECT "posthog_integration"."id",- "posthog_integration"."team_id",- "posthog_integration"."kind",- "posthog_integration"."integration_id",- "posthog_integration"."config",- "posthog_integration"."sensitive_config",- "posthog_integration"."repository_cache",- "posthog_integration"."repository_cache_updated_at",- "posthog_integration"."errors",- "posthog_integration"."created_at",- "posthog_integration"."created_by_id"- FROM "posthog_integration"- WHERE ("posthog_integration"."kind" = 'vercel'- AND "posthog_integration"."team_id" = 99999)- LIMIT 21- '''-# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.2'''SELECT "posthog_organization"."id",@@ -619,6 +593,50 @@'''# ---# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.20+ '''+ SELECT "posthog_filesystem"."team_id",+ "posthog_filesystem"."id",+ "posthog_filesystem"."path",+ "posthog_filesystem"."depth",+ "posthog_filesystem"."type",+ "posthog_filesystem"."ref",+ "posthog_filesystem"."href",+ "posthog_filesystem"."shortcut",+ "posthog_filesystem"."meta",+ "posthog_filesystem"."created_at",+ "posthog_filesystem"."created_by_id",+ "posthog_filesystem"."surface",+ "posthog_filesystem"."project_id"+ FROM "posthog_filesystem"+ WHERE (("posthog_filesystem"."surface" IS NULL+ OR "posthog_filesystem"."surface" = 'web')+ AND "posthog_filesystem"."ref" = '0001'+ AND "posthog_filesystem"."team_id" = 99999+ AND "posthog_filesystem"."type" = 'feature_flag'+ AND NOT ("posthog_filesystem"."shortcut"+ AND "posthog_filesystem"."shortcut" IS NOT NULL))+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.21+ '''+ SELECT "posthog_integration"."id",+ "posthog_integration"."team_id",+ "posthog_integration"."kind",+ "posthog_integration"."integration_id",+ "posthog_integration"."config",+ "posthog_integration"."sensitive_config",+ "posthog_integration"."repository_cache",+ "posthog_integration"."repository_cache_updated_at",+ "posthog_integration"."errors",+ "posthog_integration"."created_at",+ "posthog_integration"."created_by_id"+ FROM "posthog_integration"+ WHERE ("posthog_integration"."kind" = 'vercel'+ AND "posthog_integration"."team_id" = 99999)+ LIMIT 21+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.22'''SELECT "posthog_organization"."id","posthog_organization"."name",@@ -662,7 +680,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.21+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23'''SELECT "posthog_organizationintegration"."id","posthog_organizationintegration"."organization_id",@@ -679,7 +697,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.22+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24'''SELECT "posthog_experiment"."id","posthog_experiment"."name",@@ -722,7 +740,7 @@AND NOT "posthog_experiment"."deleted")'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.23+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25'''SELECT "posthog_experiment"."id","posthog_experiment"."name",@@ -765,7 +783,7 @@AND NOT "posthog_experiment"."deleted")'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.24+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26'''SELECT "posthog_survey"."id","posthog_survey"."team_id",@@ -810,7 +828,7 @@WHERE "posthog_survey"."linked_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.25+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27'''SELECT "posthog_earlyaccessfeature"."id","posthog_earlyaccessfeature"."team_id",@@ -828,7 +846,7 @@WHERE "posthog_earlyaccessfeature"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.26+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.28'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -881,7 +899,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.27+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29'''SELECT "posthog_dashboard"."id","posthog_dashboard"."name",@@ -910,7 +928,16 @@AND "posthog_featureflagdashboards"."feature_flag_id" = 99999)'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.28+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3+ '''+ SELECT 1 AS "a"+ FROM "posthog_organizationmembership"+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999)+ LIMIT 1+ '''+# ---+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -963,7 +990,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.29+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31'''SELECT 1 AS "a"FROM "posthog_team"@@ -972,16 +999,7 @@LIMIT 1'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.3- '''- SELECT 1 AS "a"- FROM "posthog_organizationmembership"- WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_organizationmembership"."user_id" = 99999)- LIMIT 1- '''-# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.30+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.32'''SELECT "posthog_featureflagevaluationcontext"."id","posthog_featureflagevaluationcontext"."feature_flag_id",@@ -997,7 +1015,7 @@WHERE "posthog_featureflagevaluationcontext"."feature_flag_id" = 99999'''# ----# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.31+# name: TestOrganizationFeatureFlagCopy.test_copy_feature_flag_create_new.33'''SELECT "posthog_tag"."name" AS "tag__name"FROM "posthog_taggeditem"diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 4fdcb0e9664f..938cabc64db9 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -36,6 +36,7 @@ from posthog.models.group.util import create_groupfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.project_secret_api_key import ProjectSecretAPIKey+from posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.db_context_capturing import capture_db_queries@@ -64,6 +65,7 @@ from products.feature_flags.backend.models.feature_flag import (FeatureFlagDashboards,get_feature_flags_for_team_in_cache,)+from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfigfrom products.feature_flags.backend.user_blast_radius import get_user_blast_radius, get_user_blast_radius_personsfrom products.product_analytics.backend.models.insight import Insightfrom products.product_tours.backend.models import ProductTour@@ -13214,6 +13216,38 @@ class TestFeatureFlagLimits(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "Maximum of 2 feature flags allowed per team" in str(response.json())+ @parameterized.expand(+ [+ ("override_raises_the_limit", 3, status.HTTP_201_CREATED, None),+ ("override_lowers_the_limit", 1, status.HTTP_400_BAD_REQUEST, 1),+ ("no_override_falls_back_to_global", None, status.HTTP_400_BAD_REQUEST, 2),+ ]+ )+ def test_flag_limit_uses_the_teams_effective_limit(self, _name, override, expected_status, rejected_at_limit):+ # Guards the wiring: check_flag_limits_for_team must read get_max_feature_flags_for_team,+ # not settings.MAX_FEATURE_FLAGS_PER_TEAM directly. A regression that reverts to reading+ # the global would pass every other test in this class (they all use the global) but+ # ignore a per-team override in either direction.+ self._create_flag("flag-1")+ self._create_flag("flag-2")++ config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ config.max_feature_flags_override = override+ config.save(update_fields=["max_feature_flags_override"])++ with self.settings(MAX_FEATURE_FLAGS_PER_TEAM=2):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags",+ {+ "key": "flag-3",+ "filters": {"groups": [{"rollout_percentage": 100, "properties": []}]},+ },+ )++ assert response.status_code == expected_status+ if rejected_at_limit is not None:+ assert f"Maximum of {rejected_at_limit} feature flags allowed per team" in response.json()["detail"]+class TestFeatureFlagVersions(APIBaseTest):def _create_flag_via_api(self, key="test-flag", **kwargs):diff --git a/products/feature_flags/backend/flag_limits.py b/products/feature_flags/backend/flag_limits.pynew file mode 100644index 000000000000..7cb382fcaaad--- /dev/null+++ b/products/feature_flags/backend/flag_limits.py@@ -0,0 +1,43 @@+from django.conf import settings++from posthog.models.team import Team++from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig+++def resolve_max_feature_flags(override: int | None) -> int:+ """Effective flag-count cap for a team, given its stored override."""+ return override if override is not None else settings.MAX_FEATURE_FLAGS_PER_TEAM+++def _root_team_id_for(team_id: int) -> int:+ """Project root for a team id, or the id itself when it is already the root or unknown.++ Deliberately does not raise the way posthog.models.scoping.manager.resolve_effective_team_id+ does: an unknown team here should fall back to the global default rather than 500 a flag+ create. Private because that difference makes it wrong to reach for from outside this module.+ """+ return Team.objects.filter(id=team_id).values_list("parent_team_id", flat=True).first() or team_id+++def get_max_feature_flags_override_for_team(team_id: int) -> int | None:+ # Resolved against the project root because the flag count this bounds is project-scoped:+ # RootTeamMixin.save stores every flag under the root team, and check_flag_limits_for_team+ # counts through FeatureFlag.objects, whose RootTeamManager rewrites team_id= to the root.+ # Callers also disagree on which id they pass (the viewset passes project_id, the facade+ # passes the request's own team), so reading the literal team would let a grant apply on one+ # path and not the other. The staff API's read side has the same requirement: displaying an+ # environment team's own row would show no override even when its project root has one.+ #+ # A missing config row and a row holding a null override both mean "no override", and+ # .first() returns None for both.+ return (+ TeamFeatureFlagsConfig.objects.filter(team_id=_root_team_id_for(team_id))+ .values_list("max_feature_flags_override", flat=True)+ .first()+ )+++def get_max_feature_flags_for_team(team_id: int) -> int:+ """Effective flag-count cap for a team: its root-resolved override, or the global default."""+ return resolve_max_feature_flags(get_max_feature_flags_override_for_team(team_id))diff --git a/products/feature_flags/backend/migrations/0012_teamfeatureflagsconfig_max_feature_flags_override_and_more.py b/products/feature_flags/backend/migrations/0012_teamfeatureflagsconfig_max_feature_flags_override_and_more.pynew file mode 100644index 000000000000..ad0e0b663045--- /dev/null+++ b/products/feature_flags/backend/migrations/0012_teamfeatureflagsconfig_max_feature_flags_override_and_more.py@@ -0,0 +1,44 @@+# Generated by Django 5.2.17 on 2026-08-11 22:30++import django.core.validators+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("feature_flags", "0011_clean_flag_filters_recoverable_violations"),+ ("posthog", "1298_user_stripped_alias_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamfeatureflagsconfig",+ name="max_feature_flags_override",+ field=models.PositiveIntegerField(+ blank=True,+ default=None,+ null=True,+ validators=[+ django.core.validators.MinValueValidator(1),+ django.core.validators.MaxValueValidator(20000),+ ],+ ),+ ),+ # Plain AddConstraint (not NOT VALID) is safe here: the column is added directly above and+ # is all-NULL, so validation scans nothing that can fail and the lock is brief. Same+ # reasoning as posthog/migrations/1225_team_llm_gateway_overspend_allowance_usd.py.+ migrations.AddConstraint(+ model_name="teamfeatureflagsconfig",+ constraint=models.CheckConstraint(+ condition=models.Q(+ ("max_feature_flags_override__isnull", True),+ models.Q(+ ("max_feature_flags_override__gte", 1),+ ("max_feature_flags_override__lte", 20000),+ ),+ _connector="OR",+ ),+ name="max_feature_flags_override_in_range",+ ),+ ),+ ]diff --git a/products/feature_flags/backend/migrations/max_migration.txt b/products/feature_flags/backend/migrations/max_migration.txtindex 6af005e44eac..81d461a27af8 100644--- a/products/feature_flags/backend/migrations/max_migration.txt+++ b/products/feature_flags/backend/migrations/max_migration.txt@@ -1 +1 @@-0011_clean_flag_filters_recoverable_violations+0012_teamfeatureflagsconfig_max_feature_flags_override_and_morediff --git a/products/feature_flags/backend/models/team_feature_flags_config.py b/products/feature_flags/backend/models/team_feature_flags_config.pyindex 56dcf8a02109..664a14fd6af8 100644--- a/products/feature_flags/backend/models/team_feature_flags_config.py+++ b/products/feature_flags/backend/models/team_feature_flags_config.py@@ -1,20 +1,34 @@import logging+from django.core.validators import MaxValueValidator, MinValueValidatorfrom django.db import modelsfrom posthog.models.team.extensions import register_team_extension_signallogger = logging.getLogger(__name__)+# Ceiling on a staff-granted max_feature_flags_override. The global default exists to bound the+# flag-definitions blob and the flags service's in-memory flag set, so an unbounded grant would+# reintroduce the memory risk the limit was added for. This assumes MAX_FEATURE_FLAGS_PER_TEAM+# stays below it: raising that env var past this value would leave staff able only to lower a+# team's limit. A constant rather than a setting because it feeds the mutation serializer's+# max_value, which drf-spectacular bakes into api.zod.ts as a literal, and the CHECK constraint+# below, which a migration has to name at a fixed value.+# Lives here rather than in flag_limits.py so the model can bound its own field: flag_limits+# imports this module, so the constant has to sit on the lower side of that edge.+MAX_FEATURE_FLAGS_OVERRIDE_CEILING = 20_000+class TeamFeatureFlagsConfig(models.Model):- """Internal-only team-level feature flags behavior settings.+ """Internal-only team-level feature flags settings, written by staff and never by customers.Never expose this model through a customer-facing serializer, API endpoint, or settings UI.- It gates server-controlled behavior rollouts, not customer preferences. The one exception is- the staff-only feature-flags-staff API (products/feature_flags/backend/api/staff_team_config.py,- gated by IsStaffUser), which lets staff flip minimal_flag_called_events for one team at a time- after manually verifying that team's SDK versions support the slim event shape.+ It holds server-controlled behavior rollouts and staff-granted limit overrides, not+ customer-editable preferences. The staff-only feature-flags-staff API+ (products/feature_flags/backend/api/staff_team_config.py, gated by IsStaffUser) is the only+ interactive write surface: it flips minimal_flag_called_events one team at a time after staff+ manually verify that team's SDK versions support the slim event shape, and it grants per-team+ flag-count overrides.Sanctioned writers: the team-creation signal below, get_or_create_team_extension, thestaff-only feature-flags-staff API (gated by IsStaffUser), and management commands."""@@ -30,5 +44,30 @@ class TeamFeatureFlagsConfig(models.Model):# management command.minimal_flag_called_events = models.BooleanField(default=False)+ # Raises or lowers this team's flag-count cap. Null means no override, falling back to the+ # global settings.MAX_FEATURE_FLAGS_PER_TEAM. Resolved by+ # products/feature_flags/backend/flag_limits.py, and read only when a flag is created.+ # The validators only fire under full_clean() (a Django admin ModelForm), which no writer+ # uses today; the CHECK constraint below is what actually holds the bounds on every path,+ # including a management command that writes the field directly.+ max_feature_flags_override = models.PositiveIntegerField(+ null=True,+ blank=True,+ default=None,+ validators=[MinValueValidator(1), MaxValueValidator(MAX_FEATURE_FLAGS_OVERRIDE_CEILING)],+ )++ class Meta:+ constraints = [+ models.CheckConstraint(+ name="max_feature_flags_override_in_range",+ condition=models.Q(max_feature_flags_override__isnull=True)+ | models.Q(+ max_feature_flags_override__gte=1,+ max_feature_flags_override__lte=MAX_FEATURE_FLAGS_OVERRIDE_CEILING,+ ),+ )+ ]+register_team_extension_signal(TeamFeatureFlagsConfig, logger=logger)diff --git a/products/feature_flags/backend/test/test_flag_limits.py b/products/feature_flags/backend/test/test_flag_limits.pynew file mode 100644index 000000000000..86523c46297a--- /dev/null+++ b/products/feature_flags/backend/test/test_flag_limits.py@@ -0,0 +1,49 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models.team import Team+from posthog.models.team.extensions import get_or_create_team_extension++from products.feature_flags.backend.flag_limits import get_max_feature_flags_for_team+from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig+++class TestGetMaxFeatureFlagsForTeam(BaseTest):+ @parameterized.expand(+ [+ # 777 rather than the production default of 2000, so a resolver that returned the+ # literal instead of reading the setting would fail these two rows.+ ("no_config_row", None, False, 777),+ ("null_override", None, True, 777),+ ("small_override_below_global", 1, True, 1),+ ("override_above_global", 5000, True, 5000),+ ]+ )+ def test_resolves_effective_limit(self, _name, override, has_row, expected_limit):+ if has_row:+ config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ config.max_feature_flags_override = override+ config.save(update_fields=["max_feature_flags_override"])+ else:+ # Models a legacy team that predates this field, or any lookup that hasn't+ # lazily created the row yet: get_max_feature_flags_for_team must fall back to+ # the global default rather than raising on the missing row.+ TeamFeatureFlagsConfig.objects.filter(team=self.team).delete()++ with self.settings(MAX_FEATURE_FLAGS_PER_TEAM=777):+ self.assertEqual(get_max_feature_flags_for_team(self.team.id), expected_limit)++ def test_environment_team_resolves_the_override_from_its_project_root(self):+ # Flags are project-scoped, so an environment team is charged its project's whole flag+ # count. Reading the override off the environment team instead of the root would leave a+ # granted team on the global default for every create routed through that environment.+ root_config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ root_config.max_feature_flags_override = 5000+ root_config.save(update_fields=["max_feature_flags_override"])+ environment = Team.objects.create(+ organization=self.organization, project=self.project, parent_team=self.team, name="Environment"+ )++ with self.settings(MAX_FEATURE_FLAGS_PER_TEAM=777):+ self.assertEqual(get_max_feature_flags_for_team(environment.id), 5000)diff --git a/products/feature_flags/backend/test/test_staff_team_config_api.py b/products/feature_flags/backend/test/test_staff_team_config_api.pyindex 71a4e91bf0f9..950e455dad91 100644--- a/products/feature_flags/backend/test/test_staff_team_config_api.py+++ b/products/feature_flags/backend/test/test_staff_team_config_api.py@@ -1,14 +1,23 @@from posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models.team import Teamfrom posthog.models.team.extensions import get_or_create_team_extension-from products.feature_flags.backend.api.staff_team_config import MAX_TEAM_IDS_PER_QUERY-from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig+from products.feature_flags.backend.api.staff_team_config import (+ MAX_TEAM_IDS_PER_QUERY,+ StaffTeamConfigMutationSerializer,+)+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.team_feature_flags_config import (+ MAX_FEATURE_FLAGS_OVERRIDE_CEILING,+ TeamFeatureFlagsConfig,+)LIST_URL = "/api/feature_flags_staff_team_config/"SET_URL = "/api/feature_flags_staff_team_config/set/"@@ -41,26 +50,56 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):other_team = Team.objects.create(organization=self.organization, name="Other team")config = get_or_create_team_extension(other_team, TeamFeatureFlagsConfig)config.minimal_flag_called_events = True- config.save(update_fields=["minimal_flag_called_events"])+ config.max_feature_flags_override = 5000+ config.save(update_fields=["minimal_flag_called_events", "max_feature_flags_override"])+ FeatureFlag.objects.create(team=other_team, created_by=self.user, key="other-1", filters={"groups": []})+ FeatureFlag.objects.create(team=other_team, created_by=self.user, key="other-2", filters={"groups": []})missing_id = other_team.id + 9999response = self.client.get(_list_url([self.team.id, other_team.id, missing_id]))self.assertEqual(response.status_code, status.HTTP_200_OK)- results = {row["team_id"]: row["minimal_flag_called_events"] for row in response.json()["results"]}- # self.team's row was auto-created (still False) by the team-creation signal; missing_id- # doesn't correspond to a real team and must not appear at all.- self.assertEqual(results, {self.team.id: False, other_team.id: True})+ results = {+ row["team_id"]: (+ row["minimal_flag_called_events"],+ row["max_feature_flags_override"],+ row["effective_max_feature_flags"],+ row["feature_flag_count"],+ )+ for row in response.json()["results"]+ }+ # self.team's row was auto-created (still False, no override) by the team-creation+ # signal; missing_id doesn't correspond to a real team and must not appear at all.+ # other_team's count of 2 (not 0) proves feature_flag_count reflects the real count+ # rather than a hardcoded placeholder.+ self.assertEqual(+ results,+ {+ self.team.id: (False, None, 2000, 0),+ other_team.id: (True, 5000, 5000, 2),+ },+ )def test_list_defaults_to_false_when_config_row_is_missing(self):# Models a legacy team that predates this extension (no auto-created row). list() must- # fall back to False rather than 500ing on the missing row.+ # fall back to defaults rather than 500ing on the missing row.TeamFeatureFlagsConfig.objects.filter(team=self.team).delete()response = self.client.get(_list_url([self.team.id]))self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["results"], [{"team_id": self.team.id, "minimal_flag_called_events": False}])+ self.assertEqual(+ response.json()["results"],+ [+ {+ "team_id": self.team.id,+ "minimal_flag_called_events": False,+ "max_feature_flags_override": None,+ "effective_max_feature_flags": 2000,+ "feature_flag_count": 0,+ }+ ],+ )def test_list_dedupes_repeated_team_ids(self):response = self.client.get(_list_url([self.team.id, self.team.id]))@@ -84,7 +123,16 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json(), {"team_id": self.team.id, "minimal_flag_called_events": new_value})+ self.assertEqual(+ response.json(),+ {+ "team_id": self.team.id,+ "minimal_flag_called_events": new_value,+ "max_feature_flags_override": None,+ "effective_max_feature_flags": 2000,+ "feature_flag_count": 0,+ },+ )config = TeamFeatureFlagsConfig.objects.get(team=self.team)self.assertEqual(config.minimal_flag_called_events, new_value)@@ -115,3 +163,202 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)config = TeamFeatureFlagsConfig.objects.get(team=self.team)self.assertTrue(config.minimal_flag_called_events)++ @parameterized.expand(+ [+ (+ "override_only_leaves_minimal_flag_called_events_untouched",+ {"max_feature_flags_override": 5000},+ 5000,+ False,+ ),+ (+ "minimal_flag_called_events_only_leaves_override_untouched",+ {"minimal_flag_called_events": True},+ 1234,+ True,+ ),+ ]+ )+ def test_set_partial_update_leaves_the_other_setting_untouched(+ self, _name, body, expected_override, expected_minimal_flag_called_events+ ):+ # A naive+ # `config.max_feature_flags_override = validated.get("max_feature_flags_override")` would+ # clear the override to None on every minimal_flag_called_events toggle (and vice versa),+ # since a key absent from the request becomes None under .get(). set() must build+ # update_fields from only the keys actually present in validated_data.+ config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ config.minimal_flag_called_events = False+ config.max_feature_flags_override = 1234+ config.save(update_fields=["minimal_flag_called_events", "max_feature_flags_override"])++ with (+ patch("posthog.tasks.team_metadata.update_team_metadata_cache_task"),+ patch("products.feature_flags.backend.tasks.update_team_flags_cache"),+ ):+ response = self.client.post(SET_URL, {"team_id": self.team.id, **body}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ # The staff table renders this response directly, so returning the pre-save value (the+ # `old_*` local sits in the same scope with a near-identical name) would show a stale+ # limit until reload.+ self.assertEqual(response.json()["max_feature_flags_override"], expected_override)+ self.assertEqual(response.json()["effective_max_feature_flags"], expected_override)+ config.refresh_from_db()+ self.assertEqual(config.max_feature_flags_override, expected_override)+ self.assertEqual(config.minimal_flag_called_events, expected_minimal_flag_called_events)++ def test_set_clears_the_override_when_sent_null(self):+ # DRF gives absent-vs-null three-way semantics for free (required=False, allow_null=True),+ # but only if the view actually distinguishes them. A regression that treats a present+ # `None` the same as an absent key would make the override permanently un-clearable from+ # the UI: the empty-input dialog submits an explicit null to mean "remove the override".+ config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ config.max_feature_flags_override = 5000+ config.save(update_fields=["max_feature_flags_override"])++ with (+ patch("posthog.tasks.team_metadata.update_team_metadata_cache_task"),+ patch("products.feature_flags.backend.tasks.update_team_flags_cache"),+ ):+ response = self.client.post(+ SET_URL, {"team_id": self.team.id, "max_feature_flags_override": None}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ config.refresh_from_db()+ self.assertIsNone(config.max_feature_flags_override)++ def test_set_does_not_enqueue_cache_tasks_for_an_override_only_write(self):+ # Nothing outside Django reads max_feature_flags_override (the limit is read straight+ # from Postgres on flag create), unlike minimal_flag_called_events which /flags and+ # local-eval SDKs read out of caches. A regression that enqueues the fan-out+ # unconditionally would silently make this write look cache-dependent when it isn't.+ with (+ patch("posthog.tasks.team_metadata.update_team_metadata_cache_task") as mock_metadata_task,+ patch("products.feature_flags.backend.tasks.update_team_flags_cache") as mock_flags_task,+ ):+ response = self.client.post(+ SET_URL, {"team_id": self.team.id, "max_feature_flags_override": 5000}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_metadata_task.delay.assert_not_called()+ mock_flags_task.delay.assert_not_called()++ def test_set_rejects_a_form_encoded_body(self):+ # parser_classes = [JSONParser] is the only thing stopping DRF's default_empty_html from+ # reading an absent minimal_flag_called_events as False on a limit-only write. Every other+ # test here posts JSON, so deleting that line would leave them all green while a real+ # form-encoded request silently switched the setting off.+ config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ config.minimal_flag_called_events = True+ config.save(update_fields=["minimal_flag_called_events"])++ response = self.client.post(+ SET_URL, {"team_id": self.team.id, "max_feature_flags_override": 5000}, format="multipart"+ )++ # The form body never reaches validated_data at all, which is why team_id reads as missing+ # rather than the request succeeding. Asserting the surviving setting rather than the exact+ # status keeps this pinned to the harm if DRF changes how it signals the rejection.+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["attr"], "team_id")+ config.refresh_from_db()+ self.assertTrue(config.minimal_flag_called_events)++ @parameterized.expand([("a_value", 5000), ("an_explicit_null", None)])+ def test_set_refuses_an_override_on_an_environment_team(self, _name, override):+ # Flags are project-scoped, so get_max_feature_flags_for_team reads the override off the+ # project root. A row written on an environment team would never be read, leaving staff+ # believing they had granted capacity that was silently inert.+ #+ # The null case is refused too, since the guard keys on the field being present rather than+ # on its value. Clearing an override that was never writable here is a no-op, so refusing+ # it costs nothing and keeps one answer for "can this team hold an override?". Pinned so a+ # later `validated.get(...) is not None` refactor can't flip it silently.+ environment = Team.objects.create(+ organization=self.organization, project=self.project, parent_team=self.team, name="Environment"+ )++ response = self.client.post(+ SET_URL, {"team_id": environment.id, "max_feature_flags_override": override}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn(str(self.team.id), str(response.json()))+ self.assertIsNone(TeamFeatureFlagsConfig.objects.get(team=environment).max_feature_flags_override)++ def test_list_shows_an_environment_team_its_project_roots_override(self):+ # The override is enforced against the project root, so displaying the environment team's+ # own row (which has none) would show Default while the validator enforces the root's+ # override. list() must resolve the override to the root.+ root_config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ root_config.max_feature_flags_override = 5000+ root_config.save(update_fields=["max_feature_flags_override"])+ environment = Team.objects.create(+ organization=self.organization, project=self.project, parent_team=self.team, name="Environment"+ )++ response = self.client.get(_list_url([environment.id]))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ row = response.json()["results"][0]+ self.assertEqual(row["max_feature_flags_override"], 5000)+ self.assertEqual(row["effective_max_feature_flags"], 5000)++ def test_set_response_shows_an_environment_team_its_project_roots_override(self):+ # An environment team reaches set() only on a minimal_flag_called_events-only edit, and its+ # response row still has to show the root's override rather than its own empty one, or the+ # staff table renders Default right after an edit.+ root_config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ root_config.max_feature_flags_override = 5000+ root_config.save(update_fields=["max_feature_flags_override"])+ environment = Team.objects.create(+ organization=self.organization, project=self.project, parent_team=self.team, name="Environment"+ )++ with (+ patch("posthog.tasks.team_metadata.update_team_metadata_cache_task"),+ patch("products.feature_flags.backend.tasks.update_team_flags_cache"),+ ):+ response = self.client.post(+ SET_URL, {"team_id": environment.id, "minimal_flag_called_events": True}, format="json"+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["max_feature_flags_override"], 5000)+ self.assertEqual(response.json()["effective_max_feature_flags"], 5000)+++class TestStaffTeamConfigMutationSerializerBounds(SimpleTestCase):+ # Field-level validation only, no DB, because validating a body never reaches the object-level+ # validate() or the viewset. A regression that drops min_value/max_value from the+ # serializer field (or the neither-field validate() check) would still pass every+ # DB-backed test above, since those all send a body with at least one valid setting.+ @parameterized.expand(+ [+ ("zero_rejected", {"team_id": 1, "max_feature_flags_override": 0}, "max_feature_flags_override"),+ (+ "above_ceiling_rejected",+ {"team_id": 1, "max_feature_flags_override": MAX_FEATURE_FLAGS_OVERRIDE_CEILING + 1},+ "max_feature_flags_override",+ ),+ ("neither_setting_present_rejected", {"team_id": 1}, "non_field_errors"),+ ]+ )+ def test_rejects_invalid_bodies(self, _name, data, expected_error_key):+ serializer = StaffTeamConfigMutationSerializer(data=data)+ self.assertFalse(serializer.is_valid())+ # Asserting the key, not just that validation failed: a bare assertFalse would stay green+ # if the bounds disappeared and some unrelated required field started rejecting these.+ self.assertIn(expected_error_key, serializer.errors)++ def test_accepts_the_ceiling_itself(self):+ # Pins the ceiling as inclusive. Narrowing max_value by one would keep every rejection+ # case above green while refusing the largest grant the constant advertises.+ serializer = StaffTeamConfigMutationSerializer(+ data={"team_id": 1, "max_feature_flags_override": MAX_FEATURE_FLAGS_OVERRIDE_CEILING}+ )+ self.assertTrue(serializer.is_valid())diff --git a/products/feature_flags/backend/test/test_team_feature_flags_config.py b/products/feature_flags/backend/test/test_team_feature_flags_config.pyindex cb247a7c2794..c3aa6ccd7559 100644--- a/products/feature_flags/backend/test/test_team_feature_flags_config.py+++ b/products/feature_flags/backend/test/test_team_feature_flags_config.py@@ -1,9 +1,14 @@from posthog.test.base import BaseTest+from django.db import IntegrityError, transaction++from parameterized import parameterized+from posthog.models.team import Teamfrom posthog.models.team.extensions import get_or_create_team_extensionfrom products.feature_flags.backend.models import TeamFeatureFlagsConfig+from products.feature_flags.backend.models.team_feature_flags_config import MAX_FEATURE_FLAGS_OVERRIDE_CEILINGclass TestTeamFeatureFlagsConfig(BaseTest):@@ -19,3 +24,37 @@ class TestTeamFeatureFlagsConfig(BaseTest):config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)self.assertFalse(config.minimal_flag_called_events)++ @parameterized.expand(+ [+ ("above_the_ceiling", MAX_FEATURE_FLAGS_OVERRIDE_CEILING + 1),+ ("zero", 0),+ ]+ )+ def test_database_rejects_an_out_of_range_override(self, _name, value):+ # The staff serializer's bounds are the only other guard, and .save() runs neither the+ # serializer nor the field validators. Without the CHECK constraint a management command+ # writing this field directly could grant an unbounded limit, which is the memory risk the+ # ceiling exists to prevent.+ config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ config.max_feature_flags_override = value++ with self.assertRaises(IntegrityError), transaction.atomic():+ config.save(update_fields=["max_feature_flags_override"])++ @parameterized.expand(+ [+ ("the_ceiling_itself", MAX_FEATURE_FLAGS_OVERRIDE_CEILING),+ ("one", 1),+ ("no_override", None),+ ]+ )+ def test_database_accepts_an_in_range_override(self, _name, value):+ # Pins both ends as inclusive and keeps null writable, so a constraint tightened by one+ # would fail here rather than in production.+ config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)+ config.max_feature_flags_override = value+ config.save(update_fields=["max_feature_flags_override"])++ config.refresh_from_db()+ self.assertEqual(config.max_feature_flags_override, value)diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex f4d09a6ae6e3..7cf63b2a3f26 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -177,6 +177,15 @@ export interface StaffTeamConfigApi {team_id: number/** Whether this team's SDKs receive the slim $feature_flag_called event shape (omitting fields only needed for experiments) instead of the full legacy shape. */minimal_flag_called_events: boolean+ /**+ * Per-team override for the maximum number of feature flags this team may create, or null when the team uses the global default.+ * @nullable+ */+ max_feature_flags_override: number | null+ /** The flag-count limit actually enforced for this team: the override when one is set, otherwise the global MAX_FEATURE_FLAGS_PER_TEAM setting. */+ effective_max_feature_flags: number+ /** Number of feature flags the team has today, excluding soft-deleted ones, counted the same way the limit is enforced. */+ feature_flag_count: number}export interface StaffTeamConfigListResponseApi {@@ -187,8 +196,15 @@ export interface StaffTeamConfigListResponseApi {export interface StaffTeamConfigMutationApi {/** Team id to update. Exactly one team per request. */team_id: number- /** New value for the team's minimal_flag_called_events setting. Only set true after confirming that team's SDK versions support the slim $feature_flag_called event shape. */- minimal_flag_called_events: boolean+ /** New value for the team's minimal_flag_called_events setting. Omit to leave it unchanged. Only set true after confirming that team's SDK versions support the slim $feature_flag_called event shape. */+ minimal_flag_called_events?: boolean+ /**+ * New per-team flag-count limit (1-20,000). Send null to clear the override so the team falls back to the global default. Omit to leave it unchanged.+ * @minimum 1+ * @maximum 20000+ * @nullable+ */+ max_feature_flags_override?: number | null}export interface StaffTeamResultApi {@@ -204,6 +220,11 @@ export interface StaffTeamResultApi {organization_name: string/** Project id the team belongs to. */project_id: number+ /**+ * Project root team id when this team is an environment, or null when it is the root. The flag limit is set on the root, so a team with this set cannot take an override.+ * @nullable+ */+ parent_team_id: number | null}export interface StaffTeamSearchResponseApi {diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.tsindex fbe4b114157a..ba2a2c520a65 100644--- a/products/feature_flags/frontend/generated/api.ts+++ b/products/feature_flags/frontend/generated/api.ts@@ -259,12 +259,16 @@ export const getFeatureFlagsStaffTeamConfigListUrl = (params: FeatureFlagsStaffT}/**- * Staff-only, unscoped read/write for TeamFeatureFlagsConfig (currently just- * minimal_flag_called_events).+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: the minimal_flag_called_events+ * rollout gate and the per-team feature-flag count override.*- * Single-team writes only, by design: this setting is meant to be flipped one team at a time- * after staff manually verify that team's SDK versions support the slim $feature_flag_called- * event shape, unlike the cache tools' bulk rebuild/clear.+ * Single-team writes only, by design. minimal_flag_called_events is flipped one team at a time+ * after staff verify that team's SDK versions support the slim $feature_flag_called event shape,+ * and max_feature_flags_override is a per-customer capacity grant. Neither is a bulk operation,+ * unlike the cache tools' rebuild and clear.+ *+ * set() takes partial updates: omit a setting to leave it unchanged, and send+ * max_feature_flags_override as null to clear the override.** Registered on the root router so it is not team-nested; staff act on teams they do not* belong to, same as staff_cache.py / staff_teams.py.@@ -284,12 +288,16 @@ export const getFeatureFlagsStaffTeamConfigSetCreateUrl = () => {}/**- * Staff-only, unscoped read/write for TeamFeatureFlagsConfig (currently just- * minimal_flag_called_events).+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: the minimal_flag_called_events+ * rollout gate and the per-team feature-flag count override.+ *+ * Single-team writes only, by design. minimal_flag_called_events is flipped one team at a time+ * after staff verify that team's SDK versions support the slim $feature_flag_called event shape,+ * and max_feature_flags_override is a per-customer capacity grant. Neither is a bulk operation,+ * unlike the cache tools' rebuild and clear.*- * Single-team writes only, by design: this setting is meant to be flipped one team at a time- * after staff manually verify that team's SDK versions support the slim $feature_flag_called- * event shape, unlike the cache tools' bulk rebuild/clear.+ * set() takes partial updates: omit a setting to leave it unchanged, and send+ * max_feature_flags_override as null to clear the override.** Registered on the root router so it is not team-nested; staff act on teams they do not* belong to, same as staff_cache.py / staff_teams.py.diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex 277775e0e23b..026e29b5550a 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -68,22 +68,37 @@ export const FeatureFlagsStaffCacheRebuildCreateBody = /* @__PURE__ */ zod.objec})/**- * Staff-only, unscoped read/write for TeamFeatureFlagsConfig (currently just- * minimal_flag_called_events).+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: the minimal_flag_called_events+ * rollout gate and the per-team feature-flag count override.*- * Single-team writes only, by design: this setting is meant to be flipped one team at a time- * after staff manually verify that team's SDK versions support the slim $feature_flag_called- * event shape, unlike the cache tools' bulk rebuild/clear.+ * Single-team writes only, by design. minimal_flag_called_events is flipped one team at a time+ * after staff verify that team's SDK versions support the slim $feature_flag_called event shape,+ * and max_feature_flags_override is a per-customer capacity grant. Neither is a bulk operation,+ * unlike the cache tools' rebuild and clear.+ *+ * set() takes partial updates: omit a setting to leave it unchanged, and send+ * max_feature_flags_override as null to clear the override.** Registered on the root router so it is not team-nested; staff act on teams they do not* belong to, same as staff_cache.py / staff_teams.py.*/+export const featureFlagsStaffTeamConfigSetCreateBodyMaxFeatureFlagsOverrideMax = 20000+export const FeatureFlagsStaffTeamConfigSetCreateBody = /* @__PURE__ */ zod.object({team_id: zod.number().describe('Team id to update. Exactly one team per request.'),minimal_flag_called_events: zod.boolean()+ .optional()+ .describe(+ "New value for the team's minimal_flag_called_events setting. Omit to leave it unchanged. Only set true after confirming that team's SDK versions support the slim $feature_flag_called event shape."+ ),+ max_feature_flags_override: zod+ .number()+ .min(1)+ .max(featureFlagsStaffTeamConfigSetCreateBodyMaxFeatureFlagsOverrideMax)+ .nullish().describe(- "New value for the team's minimal_flag_called_events setting. Only set true after confirming that team's SDK versions support the slim $feature_flag_called event shape."+ 'New per-team flag-count limit (1-20,000). Send null to clear the override so the team falls back to the global default. Omit to leave it unchanged.'),})diff --git a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsxindex d51da42fc3a6..417b890b66fa 100644--- a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx+++ b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx@@ -1,10 +1,11 @@import { useActions, useAsyncActions, useValues } from 'kea'-import { IconEye } from '@posthog/icons'+import { IconEye, IconPencil } from '@posthog/icons'import {LemonBanner,LemonButton,LemonDialog,+ LemonInput,LemonSwitch,LemonTable,LemonTableColumns,@@ -13,15 +14,19 @@ import {import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { TZLabel } from 'lib/components/TZLabel'+import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonProgress } from 'lib/lemon-ui/LemonProgress'import { truncate } from 'lib/utils/strings'+import { featureFlagsStaffTeamConfigSetCreateBodyMaxFeatureFlagsOverrideMax } from '../generated/api.zod'import {CACHE_LABELS,featureFlagsStaffToolsLogic,+ parseFlagLimit,StaffCacheEntryStatus,StaffCacheKind,StaffReadableCacheKind,+ StaffTeamConfig,StaffTeamResult,StaffWarmRun,} from './featureFlagsStaffToolsLogic'@@ -30,6 +35,9 @@ import { StaffTeamSearchInput } from './StaffTeamSearchInput'const NO_SELECTION_REASON = 'Select at least one team'+// Sourced from the generated zod schema so the input bound can't drift from the serializer's.+const MAX_FLAG_LIMIT = featureFlagsStaffTeamConfigSetCreateBodyMaxFeatureFlagsOverrideMax+const ALL_CACHES: StaffCacheKind[] = ['evaluation', 'definitions']const READABLE_CACHE_KINDS: StaffReadableCacheKind[] = ['evaluation', 'definitions']@@ -146,6 +154,38 @@ function CacheStatusCell({ status, onView }: { status?: StaffCacheEntryStatus; o)}+function openFlagLimitDialog(+ team: StaffTeamResult,+ config: StaffTeamConfig,+ setMaxFeatureFlagsOverride: (teamId: number, maxFeatureFlagsOverride: number | null) => Promise<void>+): void {+ LemonDialog.openForm({+ title: `Flag limit for ${team.name}`,+ description: `This team has ${config.feature_flag_count.toLocaleString()} flags, with a limit of ${config.effective_max_feature_flags.toLocaleString()}. Leave the field empty to use the default limit. A limit at or below the current count blocks all new flags for this team, including the ones surveys and experiments create.`,+ initialValues: { maxFeatureFlags: config.max_feature_flags_override ?? '' },+ shouldAwaitSubmit: true,+ content: (+ <LemonField name="maxFeatureFlags" label="Maximum flags">+ <LemonInput type="number" min={1} max={MAX_FLAG_LIMIT} placeholder="Use the default" autoFocus />+ </LemonField>+ ),+ errors: {+ maxFeatureFlags: (value) => {+ const limit = parseFlagLimit(value)+ if (limit === null || (Number.isInteger(limit) && limit >= 1 && limit <= MAX_FLAG_LIMIT)) {+ return undefined+ }+ return `Enter a whole number between 1 and ${MAX_FLAG_LIMIT.toLocaleString()}, or leave the field empty to use the default.`+ },+ },+ onSubmit: async ({ maxFeatureFlags }) => {+ // Null clears the override, which the backend reads as "fall back to the global default".+ // Awaited so the dialog keeps its submit button in a loading state until the write lands.+ await setMaxFeatureFlagsOverride(team.id, parseFlagLimit(maxFeatureFlags))+ },+ })+}+export function StaffCacheToolsTab(): JSX.Element {const {selectedTeams,@@ -159,6 +199,8 @@ export function StaffCacheToolsTab(): JSX.Element {} = useValues(featureFlagsStaffToolsLogic)const { rebuildCache, clearCache, loadCacheStatus, viewCacheEntry, setMinimalFlagCalledEvents } =useActions(featureFlagsStaffToolsLogic)+ // Async so the dialog can await the write and keep its submit button loading meanwhile.+ const { setMaxFeatureFlagsOverride } = useAsyncActions(featureFlagsStaffToolsLogic)const hasSelection = selectedTeamIds.length > 0const mutating = rebuildResultLoading || clearResultLoading@@ -210,6 +252,47 @@ export function StaffCacheToolsTab(): JSX.Element {)},},+ {+ title: 'Flag limit',+ key: 'max_feature_flags_override',+ render: (_, team) => {+ const config = teamConfigByTeamId[team.id]+ const pending = pendingTeamConfigTeamIds.includes(team.id)+ if (!config) {+ return <span className="text-secondary">Loading…</span>+ }+ const hasOverride = config.max_feature_flags_override !== null+ // Search returns environment teams too, and the endpoint refuses an override on+ // one. Keying on parent_team_id matches what the backend enforces on, so the+ // button is disabled for exactly the rows whose write would be rejected.+ const rootTeamId = team.parent_team_id+ return (+ <span className="flex items-center gap-2">+ <span>{config.effective_max_feature_flags.toLocaleString()} limit</span>+ <LemonTag type={hasOverride ? 'completion' : 'muted'}>+ {hasOverride ? 'Override' : 'Default'}+ </LemonTag>+ <span className="text-secondary">{config.feature_flag_count.toLocaleString()} in use</span>+ <LemonButton+ size="small"+ icon={<IconPencil />}+ noPadding+ loading={pending}+ disabledReason={+ pending+ ? 'Update in progress'+ : rootTeamId !== null+ ? `The flag limit is set on the project's root team (#${rootTeamId})`+ : undefined+ }+ tooltip="Edit this team's flag limit"+ onClick={() => openFlagLimitDialog(team, config, setMaxFeatureFlagsOverride)}+ data-attr="ff-staff-team-config-max-feature-flags-override"+ />+ </span>+ )+ },+ },...READABLE_CACHE_KINDS.map((cacheKind) => ({title: CACHE_LABELS[cacheKind],key: cacheKind,diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.tsindex 0d85501718da..fae333e63db4 100644--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts@@ -6,7 +6,8 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { featureFlagsStaffToolsLogic, StaffTeamResult } from './featureFlagsStaffToolsLogic'+import type { StaffTeamConfigMutationApi } from '../generated/api.schemas'+import { featureFlagsStaffToolsLogic, parseFlagLimit, StaffTeamResult } from './featureFlagsStaffToolsLogic'jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({lemonToast: { success: jest.fn(), warning: jest.fn(), error: jest.fn() },@@ -19,6 +20,8 @@ const TEAM: StaffTeamResult = {organization_id: 'org-uuid',organization_name: 'Acme Org',project_id: 5,+ // Null marks a project root, which is the team the flag limit can be set on.+ parent_team_id: null,}describe('featureFlagsStaffToolsLogic', () => {@@ -368,6 +371,25 @@ describe('featureFlagsStaffToolsLogic', () => {})})+ it("surfaces the server's reason when the write is rejected", async () => {+ // The endpoint refuses an override on an environment team, and the dialog's numeric+ // bounds can't catch that. A bare `catch` would replace this with the generic failure+ // message, leaving the operator no way to tell a refusal from a network blip.+ useMocks({+ post: {+ [SET_URL]: () => [+ 400,+ { type: 'validation_error', code: 'invalid', detail: 'Team 5 is an environment of project 3.' },+ ],+ },+ })++ logic.actions.setMaxFeatureFlagsOverride(5, 500)+ await expectLogic(logic).toDispatchActions(['teamConfigMutationSettled'])++ expect(lemonToast.error).toHaveBeenCalledWith('Team 5 is an environment of project 3.')+ })+it('only sends one mutation request when double-submitted for the same team', async () => {const handleSet = jest.fn(() => [200, { team_id: 5, minimal_flag_called_events: true }])useMocks({ post: { [SET_URL]: handleSet } })@@ -381,5 +403,87 @@ describe('featureFlagsStaffToolsLogic', () => {expect(handleSet).toHaveBeenCalledTimes(1)})++ it.each([500, null])('setMaxFeatureFlagsOverride(%p) sends only its own field', async (override) => {+ let lastBody: StaffTeamConfigMutationApi | undefined+ useMocks({+ // Seeded with the full row so the response below is a genuinely partial one, and+ // the merge has something to preserve.+ get: {+ [TEAM_CONFIG_URL]: {+ results: [+ {+ team_id: 5,+ minimal_flag_called_events: true,+ max_feature_flags_override: null,+ effective_max_feature_flags: 2000,+ feature_flag_count: 7,+ },+ ],+ },+ },+ post: {+ [SET_URL]: async ({ request }: { request: Request }) => {+ lastBody = await request.json()+ return [200, { team_id: 5, max_feature_flags_override: override }]+ },+ },+ })++ logic.actions.setSelectedTeamIds([5])+ await expectLogic(logic).toDispatchActions(['loadTeamConfigSuccess'])++ logic.actions.setMaxFeatureFlagsOverride(5, override)+ // Drives the pencil button's loading state and disabledReason while the write is in+ // flight; without it staff get no feedback on a click that issues a request.+ expect(logic.values.pendingTeamConfigTeamIds).toEqual([5])+ await expectLogic(logic).toDispatchActions(['teamConfigMutationSucceeded', 'teamConfigMutationSettled'])+ expect(logic.values.pendingTeamConfigTeamIds).toEqual([])++ // Sending a stale minimal_flag_called_events alongside the limit would silently+ // revert a concurrent staff change to that setting, which is why the backend takes+ // partial updates and each mutation sends only the field it owns.+ expect(lastBody).toEqual({ team_id: 5, max_feature_flags_override: override })+ // The fields the response omits keep the values list() fetched. Replacing the row+ // instead of merging would blank the whole Flag limit cell to "Loading…" after a save.+ expect(logic.values.teamConfigByTeamId[5]).toEqual({+ team_id: 5,+ minimal_flag_called_events: true,+ max_feature_flags_override: override,+ effective_max_feature_flags: 2000,+ feature_flag_count: 7,+ })+ })++ it('only allows one request in flight per team across both mutations', async () => {+ const handleSet = jest.fn(() => [200, { team_id: 5, minimal_flag_called_events: true }])+ useMocks({ post: { [SET_URL]: handleSet } })++ // Two separate in-flight guards, one per mutation, would let a switch toggle and a+ // limit save fly concurrently for one team. Each response carries the whole row, so+ // whichever landed second would clobber the other's field.+ await expectLogic(logic, () => {+ logic.actions.setMinimalFlagCalledEvents(5, true)+ logic.actions.setMaxFeatureFlagsOverride(5, 500)+ }).toFinishAllListeners()++ expect(handleSet).toHaveBeenCalledTimes(1)+ })+ })++ describe('parseFlagLimit', () => {+ // Both "empty" branches are load-bearing and neither is reachable from the other's test.+ // LemonInput type="number" reports a cleared field as NaN via valueAsNumber, while a field+ // the operator never touched still holds the '' the dialog seeded. Drop the NaN branch and+ // clearing an override fails validation; drop the '' branch and an untouched field submits+ // Number('') === 0, which the serializer's min_value rejects.+ it.each([+ ['', null],+ [NaN, null],+ [500, 500],+ [1, 1],+ ])('parseFlagLimit(%p) is %p', (value, expected) => {+ expect(parseFlagLimit(value)).toEqual(expected)+ })})})diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.tsindex 11959a183d11..48add22d0bd9 100644--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts@@ -2,6 +2,7 @@ import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selimport { loaders } from 'kea-loaders'import { urlToAction } from 'kea-router'+import { ApiError } from 'lib/api-error'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import {@@ -22,6 +23,7 @@ import type {StaffCacheMutationResponseApi,StaffCacheTeamStatusApi,StaffTeamConfigApi,+ StaffTeamConfigMutationApi,StaffTeamResultApi,StaffWarmRunApi,StaffWarmRunCancelResponseApi,@@ -46,6 +48,18 @@ const SEARCH_DEBOUNCE_MS = 300const WARM_RUN_ACTIVE_POLL_MS = 5000const WARM_RUN_IDLE_POLL_MS = 30000+const appendTeamId = (state: number[], { teamId }: { teamId: number }): number[] =>+ state.includes(teamId) ? state : [...state, teamId]++// LemonInput type="number" reports an emptied field as NaN via valueAsNumber, while a field the+// operator never touched still holds the '' it was seeded with. Both mean "no override", so+// neither check can be dropped: without the NaN branch, clearing a populated field fails+// validation; without the '' branch, an untouched empty field submits Number('') === 0.+export const parseFlagLimit = (value: unknown): number | null => {+ const limit = Number(value)+ return value === '' || Number.isNaN(limit) ? null : limit+}+export type StaffTeamResult = StaffTeamResultApiexport type StaffCacheTeamStatus = StaffCacheTeamStatusApiexport type StaffCacheEntryStatus = StaffCacheTeamStatusApi['evaluation']@@ -216,6 +230,13 @@ export interface featureFlagsStaffToolsLogicActions {seedTeamFromDeepLink: (teamId: number) => {teamId: number}+ setMaxFeatureFlagsOverride: (+ teamId: number,+ maxFeatureFlagsOverride: number | null+ ) => {+ maxFeatureFlagsOverride: number | null+ teamId: number+ }setMinimalFlagCalledEvents: (teamId: number,minimalFlagCalledEvents: boolean@@ -284,6 +305,10 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(teamId,minimalFlagCalledEvents,}),+ setMaxFeatureFlagsOverride: (teamId: number, maxFeatureFlagsOverride: number | null) => ({+ teamId,+ maxFeatureFlagsOverride,+ }),teamConfigMutationSucceeded: (teamConfig: StaffTeamConfig) => ({ teamConfig }),teamConfigMutationSettled: (teamId: number) => ({ teamId }),}),@@ -388,7 +413,7 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>([] as number[],{setSelectedTeamIds: (_, { teamIds }) => teamIds,- seedTeamFromDeepLink: (state, { teamId }) => (state.includes(teamId) ? state : [...state, teamId]),+ seedTeamFromDeepLink: appendTeamId,},],// Accumulate team display info (name/org/token) from every search so the@@ -421,19 +446,25 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(// Patches the matching row in place with a confirmed single-row mutation result, same as// scoutFleetLogic.ts's patchScoutConfigLocally: a loader-owned key can take extra action// handlers from a plain reducers() block alongside its auto-generated load handlers.+ // Merged rather than replaced because the response shape is a runtime contract the+ // TypeScript types can't verify: if set() ever stops returning one of the fields, merging+ // keeps the value list() already fetched instead of blanking that column.teamConfig: [[] as StaffTeamConfig[],{teamConfigMutationSucceeded: (state, { teamConfig }) =>- state.map((config) => (config.team_id === teamConfig.team_id ? teamConfig : config)),+ state.map((config) =>+ config.team_id === teamConfig.team_id ? { ...config, ...teamConfig } : config+ ),},],- // Reactive per-row in-flight flag for the switch's `loading`/`disabledReason` props.+ // Reactive per-row in-flight flag for the row controls' `loading`/`disabledReason` props.+ // Both mutations share it, so editing either setting disables the whole row.pendingTeamConfigTeamIds: [[] as number[],{- setMinimalFlagCalledEvents: (state, { teamId }) =>- state.includes(teamId) ? state : [...state, teamId],+ setMinimalFlagCalledEvents: appendTeamId,+ setMaxFeatureFlagsOverride: appendTeamId,teamConfigMutationSettled: (state, { teamId }) => state.filter((id) => id !== teamId),},],@@ -470,6 +501,35 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(actions.loadCacheStatus()}+ // One mutation in flight per team: each response carries the whole row, so a concurrent+ // pair would overwrite each other's field. The `Set` is non-reactive on purpose, guarding+ // a duplicate submit that races ahead of `pendingTeamConfigTeamIds`' re-render.+ const mutateTeamConfig = async (+ teamId: number,+ body: Omit<StaffTeamConfigMutationApi, 'team_id'>,+ settingLabel: string+ ): Promise<void> => {+ const inFlight: Set<number> = (cache.inFlightTeamConfigTeamIds ??= new Set())+ if (inFlight.has(teamId)) {+ return+ }+ inFlight.add(teamId)+ try {+ const teamConfig = await featureFlagsStaffTeamConfigSetCreate({ team_id: teamId, ...body })+ actions.teamConfigMutationSucceeded(teamConfig)+ lemonToast.success(`Updated team ${teamId}'s ${settingLabel}.`)+ } catch (error) {+ // The endpoint refuses an override on an environment team and names the team to+ // set it on instead, which the dialog's numeric bounds can't catch, so surface the+ // server's sentence when there is one.+ const detail = error instanceof ApiError ? error.detail : null+ lemonToast.error(detail || `Failed to update team ${teamId}'s ${settingLabel}.`)+ } finally {+ inFlight.delete(teamId)+ actions.teamConfigMutationSettled(teamId)+ }+ }+// Re-register the poller only when the desired cadence changes, so each// tick doesn't churn the interval.const scheduleWarmRunPoll = (desiredMs: number): void => {@@ -512,30 +572,14 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(lemonToast.error('Failed to load cache entry.')actions.closeCacheEntryModal()},- setMinimalFlagCalledEvents: async ({ teamId, minimalFlagCalledEvents }) => {- // Non-reactive guard against a duplicate submit racing ahead of the- // reducer-driven `pendingTeamConfigTeamIds` re-render. Named distinctly from that- // reducer (a `number[]` for UI loading state) since this is a `Set` used only to- // dedupe in-flight submits.- const inFlight: Set<number> = (cache.inFlightTeamConfigTeamIds ??= new Set())- if (inFlight.has(teamId)) {- return- }- inFlight.add(teamId)- try {- const teamConfig = await featureFlagsStaffTeamConfigSetCreate({- team_id: teamId,- minimal_flag_called_events: minimalFlagCalledEvents,- })- actions.teamConfigMutationSucceeded(teamConfig)- lemonToast.success(`Updated team ${teamId}'s minimal flag_called events setting.`)- } catch {- lemonToast.error(`Failed to update team ${teamId}'s minimal flag_called events setting.`)- } finally {- inFlight.delete(teamId)- actions.teamConfigMutationSettled(teamId)- }- },+ setMinimalFlagCalledEvents: async ({ teamId, minimalFlagCalledEvents }) =>+ await mutateTeamConfig(+ teamId,+ { minimal_flag_called_events: minimalFlagCalledEvents },+ 'minimal flag_called events setting'+ ),+ setMaxFeatureFlagsOverride: async ({ teamId, maxFeatureFlagsOverride }) =>+ await mutateTeamConfig(teamId, { max_feature_flags_override: maxFeatureFlagsOverride }, 'flag limit'),loadWarmRunSuccess: ({ warmRun }) => {const desiredMs =warmRun?.state === 'running' && !warmRun.is_stale ? WARM_RUN_ACTIVE_POLL_MS : WARM_RUN_IDLE_POLL_MSdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 92f308ef320c..7476f2a6d7e3 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -74715,6 +74715,15 @@ export namespace Schemas {team_id: number;/** Whether this team's SDKs receive the slim $feature_flag_called event shape (omitting fields only needed for experiments) instead of the full legacy shape. */minimal_flag_called_events: boolean;+ /**+ * Per-team override for the maximum number of feature flags this team may create, or null when the team uses the global default.+ * @nullable+ */+ max_feature_flags_override: number | null;+ /** The flag-count limit actually enforced for this team: the override when one is set, otherwise the global MAX_FEATURE_FLAGS_PER_TEAM setting. */+ effective_max_feature_flags: number;+ /** Number of feature flags the team has today, excluding soft-deleted ones, counted the same way the limit is enforced. */+ feature_flag_count: number;}export interface StaffTeamConfigListResponse {@@ -74725,8 +74734,15 @@ export namespace Schemas {export interface StaffTeamConfigMutation {/** Team id to update. Exactly one team per request. */team_id: number;- /** New value for the team's minimal_flag_called_events setting. Only set true after confirming that team's SDK versions support the slim $feature_flag_called event shape. */- minimal_flag_called_events: boolean;+ /** New value for the team's minimal_flag_called_events setting. Omit to leave it unchanged. Only set true after confirming that team's SDK versions support the slim $feature_flag_called event shape. */+ minimal_flag_called_events?: boolean;+ /**+ * New per-team flag-count limit (1-20,000). Send null to clear the override so the team falls back to the global default. Omit to leave it unchanged.+ * @minimum 1+ * @maximum 20000+ * @nullable+ */+ max_feature_flags_override?: number | null;}export interface StaffTeamResult {@@ -74742,6 +74758,11 @@ export namespace Schemas {organization_name: string;/** Project id the team belongs to. */project_id: number;+ /**+ * Project root team id when this team is an environment, or null when it is the root. The flag limit is set on the root, so a team with this set cannot take an override.+ * @nullable+ */+ parent_team_id: number | null;}export interface StaffTeamSearchResponse {