: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): add staff tool to set flag evaluations mode (#106290)
Phil Haack57cdccc027bb
diff --git a/products/feature_flags/backend/api/staff_team_config.py b/products/feature_flags/backend/api/staff_team_config.pyindex 8e48697922ef..ef325df756d9 100644--- a/products/feature_flags/backend/api/staff_team_config.py+++ b/products/feature_flags/backend/api/staff_team_config.py@@ -1,5 +1,6 @@from typing import Any+from django.db import transactionfrom django.db.models import Countimport structlog@@ -9,6 +10,7 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import NotFoundfrom rest_framework.parsers import JSONParserfrom rest_framework.permissions import IsAuthenticated+from rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.mixins import validated_requestfrom posthog.helpers.impersonation import is_impersonated@@ -18,6 +20,12 @@ from posthog.permissions import IsStaffUserfrom products.feature_flags.backend.api.staff_cache import _team_ids_fieldfrom products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_mode+from products.feature_flags.backend.flag_evaluations_mode import (+ OrganizationModeChange,+ UnknownIdsError,+ get_organizations_of_teams,+ set_organization_flag_evaluations_mode,+)from products.feature_flags.backend.flag_limits import (get_max_feature_flags_override_for_team,resolve_max_feature_flags,@@ -38,6 +46,10 @@ logger = structlog.get_logger(__name__)# value today by coincidence, not by requirement.MAX_TEAM_IDS_PER_QUERY = 50+# Caps the team ids of one flag_evaluations_mode write, which bounds the organizations that one+# transaction writes. Each team id adds at most one organization.+MAX_IDS_PER_MODE_WRITE = 50+MUTABLE_SETTINGS = ("minimal_flag_called_events", "property_matching_version", "max_feature_flags_override")@@ -156,14 +168,82 @@ class StaffTeamConfigMutationSerializer(serializers.Serializer):return attrs+class StaffFlagEvaluationsModeMutationSerializer(serializers.Serializer):+ flag_evaluations_mode = serializers.ChoiceField(+ choices=FlagEvaluationsMode.choices,+ help_text=(+ "Target flag_evaluations mode. 0 reads events, 1 reads flag_evaluations, 2 also stops writing "+ "$feature_flag_called to events. Ingestion ignores 2 until its support for 2 deploys, so 2 acts "+ "as 1 until then."+ ),+ )+ team_ids = serializers.ListField(+ child=serializers.IntegerField(),+ min_length=1,+ max_length=MAX_IDS_PER_MODE_WRITE,+ help_text=(+ f"Teams whose organizations to move (max {MAX_IDS_PER_MODE_WRITE}). The mode belongs to the "+ "organization, so the write moves every team of each organization that owns one of these teams."+ ),+ )+ allow_downgrade = serializers.BooleanField(+ default=False,+ help_text=(+ "Also lower organizations that are above the target mode. Once ingestion acts on mode 2, lowering "+ "an organization from 2 leaves a gap in the events table for the time it spent on 2."+ ),+ )+ dry_run = serializers.BooleanField(+ default=False,+ help_text="Report what the write would change, and write nothing.",+ )+++@extend_schema_serializer(component_name="StaffOrganizationModeChange")+class StaffOrganizationModeChangeSerializer(DataclassSerializer):+ current_mode = serializers.ChoiceField(+ choices=FlagEvaluationsMode.choices, help_text="The organization's mode before the write."+ )+ target_mode = serializers.ChoiceField(choices=FlagEvaluationsMode.choices, help_text="The target mode.")++ class Meta:+ dataclass = OrganizationModeChange+ exclude = ["organization_created_at"]+ extra_kwargs = {+ "organization_id": {"help_text": "Organization id."},+ "organization_name": {"help_text": "Organization name."},+ "team_count": {"help_text": "Teams of the organization. They all read the organization's mode."},+ "changed": {+ "help_text": "True when the write moved the organization to the target mode, or would on a dry run."+ },+ "left_above_mode": {+ "help_text": "True when the organization is above the target mode and stays there, because allow_downgrade is not set."+ },+ }+++class StaffFlagEvaluationsModeResponseSerializer(serializers.Serializer):+ flag_evaluations_mode = serializers.ChoiceField(+ choices=FlagEvaluationsMode.choices, help_text="The target mode of the request."+ )+ dry_run = serializers.BooleanField(help_text="True when the request wrote nothing.")+ organizations = StaffOrganizationModeChangeSerializer(+ many=True, help_text="One entry per organization the request covers, oldest organization first."+ )++class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):"""Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and theper-team feature-flag count override.- Single-team writes only, by design. Rollout settings are changed after staff verify SDK+ set() writes one team only, by design. Rollout settings are changed after staff verify SDKcompatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a- bulk operation, unlike the cache tools' rebuild and clear.+ bulk operation, unlike the cache tools' rebuild and clear. flag_evaluations_mode belongs to the+ organization, and only set_flag_evaluations_mode() writes it, for the organizations of the given+ teams. It uses the same helpers as the set_flag_evaluations_mode command, including the guard+ against lowering an organization, and it writes every organization of a request in one+ transaction.set() takes partial updates: omit a setting to leave it unchanged, and sendmax_feature_flags_override as null to clear the override.@@ -334,3 +414,47 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):feature_flag_count=FeatureFlag.objects.filter(team_id=team.id).count(),))++ @validated_request(+ request_serializer=StaffFlagEvaluationsModeMutationSerializer,+ responses={200: OpenApiResponse(response=StaffFlagEvaluationsModeResponseSerializer)},+ )+ @action(methods=["POST"], detail=False)+ def set_flag_evaluations_mode(self, request: request.Request, **kwargs) -> response.Response:+ validated = request.validated_data+ mode = FlagEvaluationsMode(validated["flag_evaluations_mode"])+ allow_downgrade: bool = validated["allow_downgrade"]+ dry_run: bool = validated["dry_run"]++ team_ids: list[int] = validated["team_ids"]+ try:+ organizations = get_organizations_of_teams(team_ids)+ except UnknownIdsError as error:+ raise NotFound(str(error)) from error++ # One transaction across organizations, so the request applies in full or not at all.+ with transaction.atomic():+ changes = [+ set_organization_flag_evaluations_mode(+ organization, mode, allow_downgrade=allow_downgrade, dry_run=dry_run+ )+ for organization in organizations+ ]++ if not dry_run:+ logger.info(+ "flags_staff_flag_evaluations_mode_updated",+ staff_user_id=request.user.id,+ was_impersonated=is_impersonated(request),+ flag_evaluations_mode=mode.value,+ allow_downgrade=allow_downgrade,+ team_ids=team_ids,+ organization_ids=[str(organization.id) for organization in organizations],+ organizations_changed=sum(change.changed for change in changes),+ )++ return response.Response(+ StaffFlagEvaluationsModeResponseSerializer(+ {"flag_evaluations_mode": mode.value, "dry_run": dry_run, "organizations": changes}+ ).data+ )diff --git a/products/feature_flags/backend/api/staff_teams.py b/products/feature_flags/backend/api/staff_teams.pyindex 86d14d6b57ee..a31976f6985b 100644--- a/products/feature_flags/backend/api/staff_teams.py+++ b/products/feature_flags/backend/api/staff_teams.py@@ -7,6 +7,7 @@ from rest_framework.permissions import IsAuthenticatedfrom posthog.api.mixins import validated_requestfrom posthog.models.team import Teamfrom posthog.permissions import IsStaffUser+from posthog.uuidt import UUIDTDEFAULT_LIMIT = 25MAX_LIMIT = 100@@ -17,9 +18,9 @@ class StaffTeamSearchQuerySerializer(serializers.Serializer):search = serializers.CharField(help_text=("Search string matched against team id (exact), api_token (exact), team name (partial), "- f"or organization name (partial). Non-numeric queries must be at least {MIN_SEARCH_LENGTH} "- "characters so an empty or single-letter query never returns half the table; a numeric team-id "- "lookup is allowed at a single digit."+ "organization name (partial), or organization id (exact). Non-numeric queries must be at least "+ f"{MIN_SEARCH_LENGTH} characters so an empty or single-letter query never returns half the table; "+ "a numeric team-id lookup is allowed at a single digit."),)limit = serializers.IntegerField(@@ -98,6 +99,8 @@ class FeatureFlagsStaffTeamSearchViewSet(viewsets.ViewSet):query = Q(name__icontains=search) | Q(api_token=search) | Q(organization__name__icontains=search)if search.isdecimal():query |= Q(id=int(search))+ if UUIDT.is_valid_uuid(search):+ query |= Q(organization_id=search)# icontains on name/organization__name forces a sequential scan (no btree-usable index);# acceptable today given staff-only, low-frequency usage. Revisit with a pg_trgm index ifdiff --git a/products/feature_flags/backend/flag_evaluations_mode.py b/products/feature_flags/backend/flag_evaluations_mode.pyindex 6e1ceadfc84b..474ed7ddc1db 100644--- a/products/feature_flags/backend/flag_evaluations_mode.py+++ b/products/feature_flags/backend/flag_evaluations_mode.py@@ -1,6 +1,6 @@"""Writes of OrganizationFeatureFlagsConfig.flag_evaluations_mode, one organization at a time."""-from collections.abc import Sequence+from collections.abc import Collection, Sequencefrom datetime import datetimefrom uuid import UUID@@ -30,6 +30,11 @@ class OrganizationModeChange:left_above_mode: bool+class UnknownIdsError(Exception):+ def __init__(self, label: str, missing_ids: Collection[object]) -> None:+ super().__init__(f"Unknown {label} id(s): {', '.join(sorted(map(str, missing_ids)))}")++def select_organizations(*, organization_ids: Sequence[UUID] | None = None, created_after: datetime | None = None) -> QuerySet[Organization]:@@ -41,6 +46,26 @@ def select_organizations(return Organization.objects.filter(created_at__gt=created_after).order_by("created_at")+def get_organizations(organization_ids: Collection[UUID]) -> list[Organization]:+ """The given organizations, oldest first.++ Raises UnknownIdsError when an id does not exist, so that a caller refuses the whole request+ and names the bad id instead of skipping it.+ """+ organizations = list(select_organizations(organization_ids=list(organization_ids)))+ if missing_ids := set(organization_ids) - {organization.id for organization in organizations}:+ raise UnknownIdsError("organization", missing_ids)+ return organizations+++def get_organizations_of_teams(team_ids: Collection[int]) -> list[Organization]:+ """The organizations that own the given teams, oldest first. Raises UnknownIdsError like get_organizations."""+ organization_id_by_team_id = dict(Team.objects.filter(id__in=team_ids).values_list("id", "organization_id"))+ if missing_ids := set(team_ids) - organization_id_by_team_id.keys():+ raise UnknownIdsError("team", missing_ids)+ return get_organizations(set(organization_id_by_team_id.values()))++def _upsert_mode(organization_id: UUID, mode: FlagEvaluationsMode, *, allow_downgrade: bool) -> bool:"""Write the mode in one statement and report whether a row changed.diff --git a/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py b/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.pyindex 167a6c91a4f4..400be56c1be4 100644--- a/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py+++ b/products/feature_flags/backend/management/commands/set_flag_evaluations_mode.py@@ -17,6 +17,8 @@ from django.core.management.base import BaseCommand, CommandError, CommandParserfrom django.db import transactionfrom products.feature_flags.backend.flag_evaluations_mode import (+ UnknownIdsError,+ get_organizations,select_organizations,set_organization_flag_evaluations_mode,)@@ -78,14 +80,13 @@ class Command(BaseCommand):allow_downgrade: bool = options["allow_downgrade"]organization_ids: list[UUID] | None = options["organization_ids"]- organizations = list(- select_organizations(organization_ids=organization_ids, created_after=options["created_after"])- )- if organization_ids is not None:- missing = set(organization_ids) - {organization.id for organization in organizations}- if missing:- # Fail before writing anything, so a mistyped id does not leave a partial run.- raise CommandError(f"Unknown organization id(s): {', '.join(sorted(map(str, missing)))}")+ if organization_ids is None:+ organizations = list(select_organizations(created_after=options["created_after"]))+ else:+ try:+ organizations = get_organizations(organization_ids)+ except UnknownIdsError as error:+ raise CommandError(str(error)) from errorverb = "Would set" if dry_run else "Set"self.stdout.write(f"{verb} mode {mode.value} ({mode.label}) on {len(organizations)} organization(s).")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 ea1832fcd753..c32cfe96562f 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,3 +1,5 @@+from uuid import UUID+from posthog.test.base import APIBaseTestfrom unittest.mock import patch@@ -6,13 +8,18 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom rest_framework import status+from posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom posthog.models.team.extensions import get_or_create_team_extension+from products.feature_flags.backend import flag_evaluations_modefrom products.feature_flags.backend.api.staff_team_config import (+ MAX_IDS_PER_MODE_WRITE,MAX_TEAM_IDS_PER_QUERY,+ StaffFlagEvaluationsModeMutationSerializer,StaffTeamConfigMutationSerializer,)+from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_modefrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfigfrom products.feature_flags.backend.models.team_feature_flags_config import (@@ -24,6 +31,7 @@ from products.feature_flags.backend.models.team_feature_flags_config import (LIST_URL = "/api/feature_flags_staff_team_config/"SET_URL = "/api/feature_flags_staff_team_config/set/"+SET_FLAG_EVALUATIONS_MODE_URL = "/api/feature_flags_staff_team_config/set_flag_evaluations_mode/"def _list_url(team_ids: list[int]) -> str:@@ -37,7 +45,20 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):self.user.is_staff = Trueself.user.save()- def test_non_staff_user_gets_403_on_list_and_set(self):+ def _stored_modes(self, *organizations: Organization) -> list[int | None]:+ stored: dict[UUID, int] = dict(+ OrganizationFeatureFlagsConfig.objects.filter(organization__in=organizations).values_list(+ "organization_id", "flag_evaluations_mode"+ )+ )+ return [stored.get(organization.id) for organization in organizations]++ def _store_mode(self, organization: Organization, mode: FlagEvaluationsMode) -> None:+ OrganizationFeatureFlagsConfig.objects.update_or_create(+ organization=organization, defaults={"flag_evaluations_mode": mode}+ )++ def test_non_staff_user_gets_403_on_every_endpoint(self):self.user.is_staff = Falseself.user.save()@@ -49,6 +70,14 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):)self.assertEqual(set_response.status_code, status.HTTP_403_FORBIDDEN)+ mode_response = self.client.post(+ SET_FLAG_EVALUATIONS_MODE_URL,+ {"flag_evaluations_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS, "team_ids": [self.team.id]},+ format="json",+ )+ self.assertEqual(mode_response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(get_organization_flag_evaluations_mode(self.organization.id), FlagEvaluationsMode.EVENTS)+def test_list_returns_config_for_existing_teams_and_skips_unknown_ids(self):other_team = Team.objects.create(organization=self.organization, name="Other team")config = get_or_create_team_extension(other_team, TeamFeatureFlagsConfig)@@ -366,6 +395,130 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):self.assertEqual(response.json()["max_feature_flags_override"], 5000)self.assertEqual(response.json()["effective_max_feature_flags"], 5000)+ @parameterized.expand(+ [+ ("raises_the_organization_below_the_mode", False, False, [1, 2], (True, False), (False, True)),+ ("dry_run_writes_nothing", True, False, [None, 2], (True, False), (False, True)),+ ("allow_downgrade_lowers_the_organization_above", False, True, [1, 1], (True, True), (False, False)),+ ]+ )+ def test_set_flag_evaluations_mode_moves_the_organizations_of_the_teams(+ self, _name, dry_run, allow_downgrade, expected_modes, expected_changed, expected_left_above_mode+ ):+ # The staff UI previews every change with dry_run, so a view that dropped dry_run on the way to+ # the helper would write on every preview. A view that dropped allow_downgrade would never+ # lower the organization on mode 2.+ OrganizationFeatureFlagsConfig.objects.filter(organization=self.organization).delete()+ sibling = Team.objects.create(organization=self.organization, name="Sibling")+ Team.objects.create(organization=self.organization, name="Not requested")+ above_organization = Organization.objects.create(name="Above")+ above_team = Team.objects.create(organization=above_organization, name="Above team")+ self._store_mode(above_organization, FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY)++ response = self.client.post(+ SET_FLAG_EVALUATIONS_MODE_URL,+ {+ "flag_evaluations_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS,+ "team_ids": [above_team.id, self.team.id, sibling.id],+ "dry_run": dry_run,+ "allow_downgrade": allow_downgrade,+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(self._stored_modes(self.organization, above_organization), expected_modes)+ self.assertEqual(+ response.json(),+ {+ "flag_evaluations_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS,+ "dry_run": dry_run,+ "organizations": [+ {+ "organization_id": str(self.organization.id),+ "organization_name": self.organization.name,+ "team_count": 3,+ "current_mode": FlagEvaluationsMode.EVENTS,+ "target_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS,+ "changed": expected_changed[0],+ "left_above_mode": expected_left_above_mode[0],+ },+ {+ "organization_id": str(above_organization.id),+ "organization_name": above_organization.name,+ "team_count": 1,+ "current_mode": FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY,+ "target_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS,+ "changed": expected_changed[1],+ "left_above_mode": expected_left_above_mode[1],+ },+ ],+ },+ )++ def test_set_flag_evaluations_mode_writes_no_organization_when_a_later_one_fails(self):+ # The helper opens no transaction, so only the view's transaction keeps an earlier+ # organization from staying written after a later one fails.+ OrganizationFeatureFlagsConfig.objects.filter(organization=self.organization).delete()+ newer_organization = Organization.objects.create(name="Newer organization")+ newer_team = Team.objects.create(organization=newer_organization, name="Newer team")+ OrganizationFeatureFlagsConfig.objects.filter(organization=newer_organization).delete()+ original_upsert = flag_evaluations_mode._upsert_mode+ upserts = 0++ # Organizations are written oldest first, so the second upsert belongs to the newer one.+ def fail_on_second_upsert(*args, **kwargs) -> bool:+ nonlocal upserts+ upserts += 1+ if upserts == 2:+ raise RuntimeError("write failed")+ return original_upsert(*args, **kwargs)++ with patch.object(flag_evaluations_mode, "_upsert_mode", side_effect=fail_on_second_upsert):+ response = self.client.post(+ SET_FLAG_EVALUATIONS_MODE_URL,+ {+ "flag_evaluations_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS,+ "team_ids": [self.team.id, newer_team.id],+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)+ self.assertEqual(upserts, 2)+ self.assertEqual(self._stored_modes(self.organization, newer_organization), [None, None])++ def test_set_flag_evaluations_mode_rejects_an_unknown_id_before_writing(self):+ missing_team_id = self.team.id + 9999++ response = self.client.post(+ SET_FLAG_EVALUATIONS_MODE_URL,+ {+ "flag_evaluations_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS,+ "team_ids": [self.team.id, missing_team_id],+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertIn(str(missing_team_id), response.json()["detail"])+ self.assertEqual(get_organization_flag_evaluations_mode(self.organization.id), FlagEvaluationsMode.EVENTS)+++class TestStaffFlagEvaluationsModeMutationSerializer(SimpleTestCase):+ @parameterized.expand(+ [+ ("missing", {}),+ ("too_many", {"team_ids": list(range(1, MAX_IDS_PER_MODE_WRITE + 2))}),+ ]+ )+ def test_rejects_invalid_team_ids(self, _name, body):+ serializer = StaffFlagEvaluationsModeMutationSerializer(+ data={"flag_evaluations_mode": FlagEvaluationsMode.READ_FLAG_EVALUATIONS, **body}+ )+ self.assertFalse(serializer.is_valid())+ self.assertIn("team_ids", serializer.errors)+class TestStaffTeamConfigMutationSerializerBounds(SimpleTestCase):# Field-level validation only, no DB, because validating a body never reaches the object-leveldiff --git a/products/feature_flags/backend/test/test_staff_teams_api.py b/products/feature_flags/backend/test/test_staff_teams_api.pyindex c8490db6eda3..ff1b04c5a3d9 100644--- a/products/feature_flags/backend/test/test_staff_teams_api.py+++ b/products/feature_flags/backend/test/test_staff_teams_api.py@@ -40,6 +40,7 @@ class TestFeatureFlagsStaffTeamSearchAPI(APIBaseTest):("partial_name", lambda self: "Searchable"),("exact_api_token", lambda self: self.searchable_team.api_token),("partial_org_name", lambda self: "Findable"),+ ("exact_org_id", lambda self: str(self.searchable_team.organization_id)),])def test_search_matches_by_field(self, _name, search_value_fn):diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex ce18dbc11a7f..e8e0d7dc11b4 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -243,6 +243,63 @@ export interface StaffTeamConfigMutationApi {max_feature_flags_override?: number | null}+export interface StaffFlagEvaluationsModeMutationApi {+ /** Target flag_evaluations mode. 0 reads events, 1 reads flag_evaluations, 2 also stops writing $feature_flag_called to events. Ingestion ignores 2 until its support for 2 deploys, so 2 acts as 1 until then.+ *+ * * `0` - Events+ * * `1` - Read flag evaluations+ * * `2` - Flag evaluations only */+ flag_evaluations_mode: FlagEvaluationsModeEnumApi+ /**+ * Teams whose organizations to move (max 50). The mode belongs to the organization, so the write moves every team of each organization that owns one of these teams.+ * @minItems 1+ * @maxItems 50+ */+ team_ids: number[]+ /** Also lower organizations that are above the target mode. Once ingestion acts on mode 2, lowering an organization from 2 leaves a gap in the events table for the time it spent on 2. */+ allow_downgrade?: boolean+ /** Report what the write would change, and write nothing. */+ dry_run?: boolean+}++export interface StaffOrganizationModeChangeApi {+ /** The organization's mode before the write.+ *+ * * `0` - Events+ * * `1` - Read flag evaluations+ * * `2` - Flag evaluations only */+ current_mode: FlagEvaluationsModeEnumApi+ /** The target mode.+ *+ * * `0` - Events+ * * `1` - Read flag evaluations+ * * `2` - Flag evaluations only */+ target_mode: FlagEvaluationsModeEnumApi+ /** Organization id. */+ organization_id: string+ /** Organization name. */+ organization_name: string+ /** Teams of the organization. They all read the organization's mode. */+ team_count: number+ /** True when the write moved the organization to the target mode, or would on a dry run. */+ changed: boolean+ /** True when the organization is above the target mode and stays there, because allow_downgrade is not set. */+ left_above_mode: boolean+}++export interface StaffFlagEvaluationsModeResponseApi {+ /** The target mode of the request.+ *+ * * `0` - Events+ * * `1` - Read flag evaluations+ * * `2` - Flag evaluations only */+ flag_evaluations_mode: FlagEvaluationsModeEnumApi+ /** True when the request wrote nothing. */+ dry_run: boolean+ /** One entry per organization the request covers, oldest organization first. */+ organizations: StaffOrganizationModeChangeApi[]+}+export interface StaffTeamResultApi {/** Team id. */id: number@@ -2009,7 +2066,7 @@ export type FeatureFlagsStaffTeamsListParams = {*/limit?: number/**- * Search string matched against team id (exact), api_token (exact), team name (partial), or organization name (partial). Non-numeric queries must be at least 2 characters so an empty or single-letter query never returns half the table; a numeric team-id lookup is allowed at a single digit.+ * Search string matched against team id (exact), api_token (exact), team name (partial), organization name (partial), or organization id (exact). Non-numeric queries must be at least 2 characters so an empty or single-letter query never returns half the table; a numeric team-id lookup is allowed at a single digit.* @minLength 1*/search: stringdiff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.tsindex c2b7a8e7c2fc..33715c64febd 100644--- a/products/feature_flags/frontend/generated/api.ts+++ b/products/feature_flags/frontend/generated/api.ts@@ -58,6 +58,8 @@ import type {StaffCacheMutationApi,StaffCacheMutationResponseApi,StaffCacheStatusResponseApi,+ StaffFlagEvaluationsModeMutationApi,+ StaffFlagEvaluationsModeResponseApi,StaffTeamConfigApi,StaffTeamConfigListResponseApi,StaffTeamConfigMutationApi,@@ -265,9 +267,13 @@ export const getFeatureFlagsStaffTeamConfigListUrl = (params: FeatureFlagsStaffT* Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and the* per-team feature-flag count override.*- * Single-team writes only, by design. Rollout settings are changed after staff verify SDK+ * set() writes one team only, by design. Rollout settings are changed after staff verify SDK* compatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a- * bulk operation, unlike the cache tools' rebuild and clear.+ * bulk operation, unlike the cache tools' rebuild and clear. flag_evaluations_mode belongs to the+ * organization, and only set_flag_evaluations_mode() writes it, for the organizations of the given+ * teams. It uses the same helpers as the set_flag_evaluations_mode command, including the guard+ * against lowering an organization, and it writes every organization of a request in one+ * transaction.** set() takes partial updates: omit a setting to leave it unchanged, and send* max_feature_flags_override as null to clear the override.@@ -293,9 +299,13 @@ export const getFeatureFlagsStaffTeamConfigSetCreateUrl = () => {* Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and the* per-team feature-flag count override.*- * Single-team writes only, by design. Rollout settings are changed after staff verify SDK+ * set() writes one team only, by design. Rollout settings are changed after staff verify SDK* compatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a- * bulk operation, unlike the cache tools' rebuild and clear.+ * bulk operation, unlike the cache tools' rebuild and clear. flag_evaluations_mode belongs to the+ * organization, and only set_flag_evaluations_mode() writes it, for the organizations of the given+ * teams. It uses the same helpers as the set_flag_evaluations_mode command, including the guard+ * against lowering an organization, and it writes every organization of a request in one+ * transaction.** set() takes partial updates: omit a setting to leave it unchanged, and send* max_feature_flags_override as null to clear the override.@@ -315,6 +325,43 @@ export const featureFlagsStaffTeamConfigSetCreate = async (})}+export const getFeatureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateUrl = () => {+ return `/api/feature_flags_staff_team_config/set_flag_evaluations_mode/`+}++/**+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and the+ * per-team feature-flag count override.+ *+ * set() writes one team only, by design. Rollout settings are changed after staff verify SDK+ * compatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a+ * bulk operation, unlike the cache tools' rebuild and clear. flag_evaluations_mode belongs to the+ * organization, and only set_flag_evaluations_mode() writes it, for the organizations of the given+ * teams. It uses the same helpers as the set_flag_evaluations_mode command, including the guard+ * against lowering an organization, and it writes every organization of a request in one+ * transaction.+ *+ * 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 featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreate = async (+ staffFlagEvaluationsModeMutationApi: StaffFlagEvaluationsModeMutationApi,+ options?: RequestInit+): Promise<StaffFlagEvaluationsModeResponseApi> => {+ return apiMutator<StaffFlagEvaluationsModeResponseApi>(+ getFeatureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateUrl(),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(staffFlagEvaluationsModeMutationApi),+ }+ )+}+export const getFeatureFlagsStaffTeamsListUrl = (params: FeatureFlagsStaffTeamsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex d6a4f3d72dbf..5130547f13d5 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -71,9 +71,13 @@ export const FeatureFlagsStaffCacheRebuildCreateBody = /* @__PURE__ */ zod.objec* Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and the* per-team feature-flag count override.*- * Single-team writes only, by design. Rollout settings are changed after staff verify SDK+ * set() writes one team only, by design. Rollout settings are changed after staff verify SDK* compatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a- * bulk operation, unlike the cache tools' rebuild and clear.+ * bulk operation, unlike the cache tools' rebuild and clear. flag_evaluations_mode belongs to the+ * organization, and only set_flag_evaluations_mode() writes it, for the organizations of the given+ * teams. It uses the same helpers as the set_flag_evaluations_mode command, including the guard+ * against lowering an organization, and it writes every organization of a request in one+ * transaction.** set() takes partial updates: omit a setting to leave it unchanged, and send* max_feature_flags_override as null to clear the override.@@ -108,6 +112,54 @@ export const FeatureFlagsStaffTeamConfigSetCreateBody = /* @__PURE__ */ zod.obje),})+/**+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and the+ * per-team feature-flag count override.+ *+ * set() writes one team only, by design. Rollout settings are changed after staff verify SDK+ * compatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a+ * bulk operation, unlike the cache tools' rebuild and clear. flag_evaluations_mode belongs to the+ * organization, and only set_flag_evaluations_mode() writes it, for the organizations of the given+ * teams. It uses the same helpers as the set_flag_evaluations_mode command, including the guard+ * against lowering an organization, and it writes every organization of a request in one+ * transaction.+ *+ * 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 featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateBodyTeamIdsMax = 50++export const featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateBodyAllowDowngradeDefault = false+export const featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateBodyDryRunDefault = false++export const FeatureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateBody = /* @__PURE__ */ zod.object({+ flag_evaluations_mode: zod+ .union([zod.literal(0), zod.literal(1), zod.literal(2)])+ .describe(+ 'Target flag_evaluations mode. 0 reads events, 1 reads flag_evaluations, 2 also stops writing $feature_flag_called to events. Ingestion ignores 2 until its support for 2 deploys, so 2 acts as 1 until then.\n\n\* `0` - Events\n\* `1` - Read flag evaluations\n\* `2` - Flag evaluations only'+ ),+ team_ids: zod+ .array(zod.number())+ .min(1)+ .max(featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateBodyTeamIdsMax)+ .describe(+ 'Teams whose organizations to move (max 50). The mode belongs to the organization, so the write moves every team of each organization that owns one of these teams.'+ ),+ allow_downgrade: zod+ .boolean()+ .default(featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateBodyAllowDowngradeDefault)+ .describe(+ 'Also lower organizations that are above the target mode. Once ingestion acts on mode 2, lowering an organization from 2 leaves a gap in the events table for the time it spent on 2.'+ ),+ dry_run: zod+ .boolean()+ .default(featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreateBodyDryRunDefault)+ .describe('Report what the write would change, and write nothing.'),+})+export const featureFlagsCopyFlagsCreateBodyTargetProjectIdsMax = 50export const featureFlagsCopyFlagsCreateBodyCopyScheduleDefault = falsediff --git a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsxindex 417b890b66fa..ad329fa4b850 100644--- a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx+++ b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx@@ -21,6 +21,7 @@ import { truncate } from 'lib/utils/strings'import { featureFlagsStaffTeamConfigSetCreateBodyMaxFeatureFlagsOverrideMax } from '../generated/api.zod'import {CACHE_LABELS,+ FLAG_EVALUATIONS_MODE_LABELS,featureFlagsStaffToolsLogic,parseFlagLimit,StaffCacheEntryStatus,@@ -31,6 +32,7 @@ import {StaffWarmRun,} from './featureFlagsStaffToolsLogic'import { StaffCacheEntryModal } from './StaffCacheEntryModal'+import { StaffFlagEvaluationsModeModal } from './StaffFlagEvaluationsModeModal'import { StaffTeamSearchInput } from './StaffTeamSearchInput'const NO_SELECTION_REASON = 'Select at least one team'@@ -197,8 +199,14 @@ export function StaffCacheToolsTab(): JSX.Element {teamConfigByTeamId,pendingTeamConfigTeamIds,} = useValues(featureFlagsStaffToolsLogic)- const { rebuildCache, clearCache, loadCacheStatus, viewCacheEntry, setMinimalFlagCalledEvents } =- useActions(featureFlagsStaffToolsLogic)+ const {+ rebuildCache,+ clearCache,+ loadCacheStatus,+ viewCacheEntry,+ setMinimalFlagCalledEvents,+ openFlagEvaluationsModeModal,+ } = useActions(featureFlagsStaffToolsLogic)// Async so the dialog can await the write and keep its submit button loading meanwhile.const { setMaxFeatureFlagsOverride } = useAsyncActions(featureFlagsStaffToolsLogic)@@ -293,6 +301,21 @@ export function StaffCacheToolsTab(): JSX.Element {)},},+ {+ title: 'Flag evaluations mode',+ key: 'flag_evaluations_mode',+ render: (_, team) => {+ const config = teamConfigByTeamId[team.id]+ if (!config) {+ return <span className="text-secondary">Loading…</span>+ }+ return (+ <LemonTag type={config.flag_evaluations_mode === 0 ? 'muted' : 'completion'}>+ {FLAG_EVALUATIONS_MODE_LABELS[config.flag_evaluations_mode]}+ </LemonTag>+ )+ },+ },...READABLE_CACHE_KINDS.map((cacheKind) => ({title: CACHE_LABELS[cacheKind],key: cacheKind,@@ -344,6 +367,15 @@ export function StaffCacheToolsTab(): JSX.Element {>Clear flag caches</LemonButton>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => openFlagEvaluationsModeModal()}+ disabledReason={!hasSelection ? NO_SELECTION_REASON : undefined}+ data-attr="ff-staff-flag-evaluations-mode-open"+ >+ Set flag evaluations mode+ </LemonButton><LemonButtontype="tertiary"size="small"@@ -364,6 +396,7 @@ export function StaffCacheToolsTab(): JSX.Element {/><StaffCacheEntryModal />+ <StaffFlagEvaluationsModeModal /></div>)}diff --git a/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsx b/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsxnew file mode 100644index 000000000000..9211cde98e3d--- /dev/null+++ b/products/feature_flags/frontend/staff/StaffFlagEvaluationsModeModal.tsx@@ -0,0 +1,161 @@+import { useActions, useValues } from 'kea'++import {+ LemonBanner,+ LemonButton,+ LemonCheckbox,+ LemonModal,+ LemonSelect,+ LemonTable,+ LemonTableColumns,+ Spinner,+} from '@posthog/lemon-ui'++import { LemonField } from 'lib/lemon-ui/LemonField'+import { pluralize } from 'lib/utils/strings'++import { FlagEvaluationsModeEnumApi, StaffOrganizationModeChangeApi } from '../generated/api.schemas'+import { FLAG_EVALUATIONS_MODE_LABELS, featureFlagsStaffToolsLogic } from './featureFlagsStaffToolsLogic'++const MODE_DESCRIPTIONS: Record<FlagEvaluationsModeEnumApi, string> = {+ 0: 'The Usage tab reads $feature_flag_called events from the events table.',+ 1: 'The Usage tab reads the flag_evaluations table, and the table is available in SQL. While the FLAG_EVALUATIONS_USAGE_TAB_FORCE_EVENTS instance setting is on, the Usage tab reads the events table instead.',+ 2: 'The Usage tab reads the flag_evaluations table, and the table is available in SQL. Ingestion also stops writing $feature_flag_called to the events table.',+}++export function StaffFlagEvaluationsModeModal(): JSX.Element {+ const {+ isFlagEvaluationsModeModalOpen,+ flagEvaluationsModeRequest,+ flagEvaluationsModePreviewLoading,+ flagEvaluationsModePreviewSummary,+ flagEvaluationsModeResultLoading,+ } = useValues(featureFlagsStaffToolsLogic)+ const {+ closeFlagEvaluationsModeModal,+ setFlagEvaluationsModeRequest,+ loadFlagEvaluationsModePreview,+ applyFlagEvaluationsMode,+ } = useActions(featureFlagsStaffToolsLogic)++ const { mode, allowDowngrade } = flagEvaluationsModeRequest++ const columns: LemonTableColumns<StaffOrganizationModeChangeApi> = [+ { title: 'Organization', dataIndex: 'organization_name' },+ { title: 'Teams', dataIndex: 'team_count' },+ {+ title: 'Current mode',+ key: 'current_mode',+ render: (_, organization) => FLAG_EVALUATIONS_MODE_LABELS[organization.current_mode],+ },+ {+ title: 'New mode',+ key: 'new_mode',+ render: (_, organization) =>+ organization.changed ? (+ FLAG_EVALUATIONS_MODE_LABELS[organization.target_mode]+ ) : (+ <span className="text-secondary">Unchanged</span>+ ),+ },+ ]++ const summary = flagEvaluationsModePreviewSummary+ const applyDisabledReason = !summary+ ? flagEvaluationsModePreviewLoading+ ? 'Wait for the preview to load'+ : 'Retry the preview first'+ : summary.organizationsChanged === 0+ ? 'No organization would change'+ : undefined+ const applyingReason = flagEvaluationsModeResultLoading ? 'Wait for the move to finish' : undefined++ return (+ <LemonModal+ title="Set flag evaluations mode"+ description="Choose which table the flag Usage tab reads $feature_flag_called data from. The mode applies to the whole organization of each selected team."+ isOpen={isFlagEvaluationsModeModalOpen}+ onClose={closeFlagEvaluationsModeModal}+ closable={!flagEvaluationsModeResultLoading}+ width={640}+ footer={+ <>+ <LemonButton+ type="secondary"+ onClick={closeFlagEvaluationsModeModal}+ disabledReason={applyingReason}+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={() => applyFlagEvaluationsMode()}+ loading={flagEvaluationsModeResultLoading}+ disabledReason={applyDisabledReason}+ data-attr="ff-staff-flag-evaluations-mode-apply"+ >+ {summary?.organizationsChanged+ ? `Move ${pluralize(summary.organizationsChanged, 'organization')}`+ : 'Move organizations'}+ </LemonButton>+ </>+ }+ >+ <div className="space-y-4">+ <LemonField.Pure label="Mode" help={MODE_DESCRIPTIONS[mode]}>+ <LemonSelect+ value={mode}+ onChange={(newMode) => setFlagEvaluationsModeRequest({ mode: newMode })}+ disabledReason={applyingReason}+ options={Object.values(FlagEvaluationsModeEnumApi).map((value) => ({+ value,+ label: FLAG_EVALUATIONS_MODE_LABELS[value],+ }))}+ />+ </LemonField.Pure>++ {mode === FlagEvaluationsModeEnumApi.Number2 && (+ <LemonBanner type="warning">+ Ingestion doesn't act on this mode yet, so it still writes $feature_flag_called to the events+ table for organizations on it. Once ingestion supports this mode, it stops those writes.+ </LemonBanner>+ )}++ <LemonCheckbox+ checked={allowDowngrade}+ onChange={(checked) => setFlagEvaluationsModeRequest({ allowDowngrade: checked })}+ disabledReason={applyingReason}+ label="Also lower organizations that are above this mode"+ />++ {flagEvaluationsModePreviewLoading ? (+ <div className="flex justify-center p-4">+ <Spinner className="text-2xl" />+ </div>+ ) : !summary ? (+ <div className="flex items-center justify-center gap-2 p-4">+ <span className="text-secondary">Couldn't load the preview.</span>+ <LemonButton type="secondary" size="small" onClick={() => loadFlagEvaluationsModePreview()}>+ Retry+ </LemonButton>+ </div>+ ) : (+ <div className="space-y-2">+ <LemonTable+ size="small"+ dataSource={summary.organizations}+ columns={columns}+ rowKey="organization_id"+ />+ {summary.organizationsLeftAboveMode > 0 && (+ <p className="text-secondary mb-0">+ {pluralize(summary.organizationsLeftAboveMode, 'organization')} above this mode will+ stay there. Select "Also lower organizations that are above this mode" to move them.+ </p>+ )}+ </div>+ )}+ </div>+ </LemonModal>+ )+}diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.tsindex fae333e63db4..3b1bc3102e86 100644--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts@@ -6,7 +6,11 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import type { StaffTeamConfigMutationApi } from '../generated/api.schemas'+import type {+ StaffFlagEvaluationsModeMutationApi,+ StaffOrganizationModeChangeApi,+ StaffTeamConfigMutationApi,+} from '../generated/api.schemas'import { featureFlagsStaffToolsLogic, parseFlagLimit, StaffTeamResult } from './featureFlagsStaffToolsLogic'jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({@@ -471,6 +475,75 @@ describe('featureFlagsStaffToolsLogic', () => {})})+ describe('flag evaluations mode', () => {+ const MODE_URL = '/api/feature_flags_staff_team_config/set_flag_evaluations_mode'++ it('previews the request as a dry run, then applies the same request', async () => {+ const bodies: StaffFlagEvaluationsModeMutationApi[] = []+ // Three organizations move, one stays above the mode, and one is already on it. A summary+ // that reads the wrong field, or counts every unchanged organization as left above, fails.+ const organizations: StaffOrganizationModeChangeApi[] = (+ [+ [0, true, false],+ [0, true, false],+ [0, true, false],+ [2, false, true],+ [1, false, false],+ ] as const+ ).map(([currentMode, changed, leftAboveMode], index) => ({+ organization_id: `org-${index}`,+ organization_name: `Org ${index}`,+ team_count: 2,+ current_mode: currentMode,+ target_mode: 1,+ changed,+ left_above_mode: leftAboveMode,+ }))+ useMocks({+ post: {+ [MODE_URL]: async ({ request }: { request: Request }) => {+ const body: StaffFlagEvaluationsModeMutationApi = await request.json()+ bodies.push(body)+ return [200, { flag_evaluations_mode: 1, dry_run: body.dry_run, organizations }]+ },+ },+ })+ logic.actions.searchTeams({ query: 'Acme' })+ await expectLogic(logic).toDispatchActions(['searchTeamsSuccess'])+ // Team 99 stands in for a deep-linked team whose search result never arrived. The request+ // must still send it, so the write covers its organization.+ logic.actions.setSelectedTeamIds([5, 99])++ logic.actions.openFlagEvaluationsModeModal()+ await expectLogic(logic).toDispatchActions(['loadFlagEvaluationsModePreviewSuccess'])+ logic.actions.setFlagEvaluationsModeRequest({ mode: 2 })+ // A preview of the previous request must not stay on screen next to an Apply button+ // that sends the new one.+ expect(logic.values.flagEvaluationsModePreview).toBeNull()+ await expectLogic(logic).toDispatchActions(['loadFlagEvaluationsModePreviewSuccess'])+ expect(logic.values.flagEvaluationsModePreviewSummary).toMatchObject({+ organizationsChanged: 3,+ organizationsLeftAboveMode: 1,+ })++ // A selection change after the preview must not widen the write past what the preview showed.+ logic.actions.setSelectedTeamIds([5, 99, 6])+ logic.actions.applyFlagEvaluationsMode()+ await expectLogic(logic).toDispatchActions(['applyFlagEvaluationsModeSuccess', 'loadTeamConfig'])++ // The preview fires on every form change, so a preview without dry_run would write the+ // mode while staff are still choosing it.+ const request = { flag_evaluations_mode: 2, allow_downgrade: false, team_ids: [5, 99] }+ expect(bodies).toEqual([+ { flag_evaluations_mode: 1, allow_downgrade: false, team_ids: [5, 99], dry_run: true },+ { ...request, dry_run: true },+ { ...request, dry_run: false },+ ])+ expect(logic.values.isFlagEvaluationsModeModalOpen).toBe(false)+ expect(lemonToast.success).toHaveBeenCalled()+ })+ })+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 fielddiff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.tsindex 48add22d0bd9..8230e64e0362 100644--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts@@ -4,6 +4,7 @@ import { urlToAction } from 'kea-router'import { ApiError } from 'lib/api-error'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { pluralize } from 'lib/utils/strings'import {featureFlagsStaffCacheClearCreate,@@ -12,16 +13,21 @@ import {featureFlagsStaffCacheRebuildCreate,featureFlagsStaffTeamConfigList,featureFlagsStaffTeamConfigSetCreate,+ featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreate,featureFlagsStaffCacheWarmRunCancelCreate,featureFlagsStaffCacheWarmRunRetrieve,featureFlagsStaffTeamsList,} from '../generated/api'import type {FeatureFlagsStaffCacheEntryRetrieveCache,+ FlagEvaluationsModeEnumApi,StaffCacheEntryResponseApi,StaffCacheKindEnumApi,StaffCacheMutationResponseApi,StaffCacheTeamStatusApi,+ StaffFlagEvaluationsModeMutationApi,+ StaffFlagEvaluationsModeResponseApi,+ StaffOrganizationModeChangeApi,StaffTeamConfigApi,StaffTeamConfigMutationApi,StaffTeamResultApi,@@ -40,6 +46,36 @@ export const CACHE_LABELS: Record<StaffReadableCacheKind, string> = {definitions: 'Definitions cache',}+// Mirrors the labels of the backend's FlagEvaluationsMode choices.+export const FLAG_EVALUATIONS_MODE_LABELS: Record<FlagEvaluationsModeEnumApi, string> = {+ 0: 'Events',+ 1: 'Read flag evaluations',+ 2: 'Flag evaluations only',+}++export interface FlagEvaluationsModeRequest {+ mode: FlagEvaluationsModeEnumApi+ allowDowngrade: boolean+}++export type FlagEvaluationsModeBody = Omit<StaffFlagEvaluationsModeMutationApi, 'dry_run'>++export interface FlagEvaluationsModePreview {+ body: FlagEvaluationsModeBody+ response: StaffFlagEvaluationsModeResponseApi+}++export interface FlagEvaluationsModePreviewSummary {+ organizations: StaffOrganizationModeChangeApi[]+ organizationsChanged: number+ organizationsLeftAboveMode: number+}++const DEFAULT_FLAG_EVALUATIONS_MODE_REQUEST: FlagEvaluationsModeRequest = {+ mode: 1,+ allowDowngrade: false,+}+const MIN_SEARCH_LENGTH = 2const SEARCH_DEBOUNCE_MS = 300@@ -67,6 +103,10 @@ export type StaffCacheMutationResponse = StaffCacheMutationResponseApiexport type StaffCacheEntry = StaffCacheEntryResponseApiexport type StaffTeamConfig = StaffTeamConfigApiexport type StaffWarmRun = StaffWarmRunApi+export type StaffFlagEvaluationsModeResponse = StaffFlagEvaluationsModeResponseApi++const organizationsChangedBy = (response: StaffFlagEvaluationsModeResponse): number =>+ response.organizations.filter((organization) => organization.changed).length// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface featureFlagsStaffToolsLogicValues {@@ -77,7 +117,15 @@ export interface featureFlagsStaffToolsLogicValues {cacheStatusLoading: booleanclearResult: StaffCacheMutationResponse | nullclearResultLoading: boolean+ flagEvaluationsModeBody: FlagEvaluationsModeBody+ flagEvaluationsModePreview: FlagEvaluationsModePreview | null+ flagEvaluationsModePreviewLoading: boolean+ flagEvaluationsModePreviewSummary: FlagEvaluationsModePreviewSummary | null+ flagEvaluationsModeRequest: FlagEvaluationsModeRequest+ flagEvaluationsModeResult: StaffFlagEvaluationsModeResponse | null+ flagEvaluationsModeResultLoading: booleanhasSeededFromDeepLink: boolean+ isFlagEvaluationsModeModalOpen: booleanknownTeams: Record<number, StaffTeamResult>pendingTeamConfigTeamIds: number[]rebuildResult: StaffCacheMutationResponse | null@@ -101,6 +149,21 @@ export interface featureFlagsStaffToolsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface featureFlagsStaffToolsLogicActions {+ applyFlagEvaluationsMode: () => any+ applyFlagEvaluationsModeFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ applyFlagEvaluationsModeSuccess: (+ flagEvaluationsModeResult: StaffFlagEvaluationsModeResponseApi,+ payload?: any+ ) => {+ flagEvaluationsModeResult: StaffFlagEvaluationsModeResponseApi+ payload?: any+ }cancelWarmRun: () => anycancelWarmRunFailure: (error: string,@@ -140,6 +203,9 @@ export interface featureFlagsStaffToolsLogicActions {closeCacheEntryModal: () => {value: true}+ closeFlagEvaluationsModeModal: () => {+ value: true+ }loadCacheStatus: (_: void) => voidloadCacheStatusFailure: (error: string,@@ -155,6 +221,27 @@ export interface featureFlagsStaffToolsLogicActions {cacheStatus: StaffCacheTeamStatusApi[]payload?: void}+ loadFlagEvaluationsModePreview: (_: void) => void+ loadFlagEvaluationsModePreviewFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFlagEvaluationsModePreviewSuccess: (+ flagEvaluationsModePreview: {+ body: FlagEvaluationsModeBody+ response: StaffFlagEvaluationsModeResponseApi+ },+ payload?: void+ ) => {+ flagEvaluationsModePreview: {+ body: FlagEvaluationsModeBody+ response: StaffFlagEvaluationsModeResponseApi+ }+ payload?: void+ }loadTeamConfig: (_: void) => voidloadTeamConfigFailure: (error: string,@@ -185,6 +272,9 @@ export interface featureFlagsStaffToolsLogicActions {warmRun: StaffWarmRunApi | nullpayload?: any}+ openFlagEvaluationsModeModal: () => {+ value: true+ }rebuildCache: ({ caches }: { caches: StaffCacheKind[] }) => {caches: StaffCacheKind[]}@@ -230,6 +320,9 @@ export interface featureFlagsStaffToolsLogicActions {seedTeamFromDeepLink: (teamId: number) => {teamId: number}+ setFlagEvaluationsModeRequest: (request: Partial<FlagEvaluationsModeRequest>) => {+ request: Partial<FlagEvaluationsModeRequest>+ }setMaxFeatureFlagsOverride: (teamId: number,maxFeatureFlagsOverride: number | null@@ -285,6 +378,13 @@ export interface featureFlagsStaffToolsLogicMeta {selectedTeams: (selectedTeamIds: number[], knownTeams: Record<number, StaffTeamResultApi>) => StaffTeamResult[]cacheStatusByTeamId: (cacheStatus: StaffCacheTeamStatusApi[]) => Record<number, StaffCacheTeamStatus>teamConfigByTeamId: (teamConfig: StaffTeamConfigApi[]) => Record<number, StaffTeamConfig>+ flagEvaluationsModeBody: (+ flagEvaluationsModeRequest: FlagEvaluationsModeRequest,+ selectedTeamIds: number[]+ ) => FlagEvaluationsModeBody+ flagEvaluationsModePreviewSummary: (+ flagEvaluationsModePreview: FlagEvaluationsModePreview | null+ ) => FlagEvaluationsModePreviewSummary | null}}@@ -311,6 +411,9 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(}),teamConfigMutationSucceeded: (teamConfig: StaffTeamConfig) => ({ teamConfig }),teamConfigMutationSettled: (teamId: number) => ({ teamId }),+ openFlagEvaluationsModeModal: true,+ closeFlagEvaluationsModeModal: true,+ setFlagEvaluationsModeRequest: (request: Partial<FlagEvaluationsModeRequest>) => ({ request }),}),loaders(({ values }) => ({teamSearchResults: [@@ -407,6 +510,39 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(},},],+ flagEvaluationsModePreview: [+ null as FlagEvaluationsModePreview | null,+ {+ loadFlagEvaluationsModePreview: async (_: void, breakpoint) => {+ // Debounced so flipping through the form sends one dry run for the final choice.+ await breakpoint(SEARCH_DEBOUNCE_MS)+ const body = values.flagEvaluationsModeBody+ const response = await featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreate({+ ...body,+ dry_run: true,+ })+ breakpoint()+ return { body, response }+ },+ },+ ],+ flagEvaluationsModeResult: [+ null as StaffFlagEvaluationsModeResponse | null,+ {+ applyFlagEvaluationsMode: async () => {+ // Sends the body the preview ran with, so the write covers the teams the preview showed+ // even if the selection changed since.+ const preview = values.flagEvaluationsModePreview+ if (!preview) {+ throw new Error('Load a preview before applying the change.')+ }+ return await featureFlagsStaffTeamConfigSetFlagEvaluationsModeCreate({+ ...preview.body,+ dry_run: false,+ })+ },+ },+ ],})),reducers({selectedTeamIds: [@@ -458,6 +594,30 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(),},],+ isFlagEvaluationsModeModalOpen: [+ false,+ {+ openFlagEvaluationsModeModal: () => true,+ closeFlagEvaluationsModeModal: () => false,+ applyFlagEvaluationsModeSuccess: () => false,+ },+ ],+ flagEvaluationsModeRequest: [+ DEFAULT_FLAG_EVALUATIONS_MODE_REQUEST,+ {+ setFlagEvaluationsModeRequest: (state, { request }) => ({ ...state, ...request }),+ },+ ],+ // Cleared when staff change the mode or downgrade option. Apply sends the body this preview+ // ran with, so a stale preview would show and apply choices that are no longer on screen. A+ // selection change does not clear it, because the write still covers only the organizations+ // of the previewed teams.+ flagEvaluationsModePreview: [+ null as FlagEvaluationsModePreview | null,+ {+ setFlagEvaluationsModeRequest: () => null,+ },+ ],// 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: [@@ -485,6 +645,27 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>((teamConfig: StaffTeamConfig[]): Record<number, StaffTeamConfig> =>Object.fromEntries(teamConfig.map((config) => [config.team_id, config])),],+ // Sends team ids and lets the server resolve their organizations, because a deep-linked team+ // can stay selected without a search result in knownTeams.+ flagEvaluationsModeBody: [+ (s) => [s.flagEvaluationsModeRequest, s.selectedTeamIds],+ (request: FlagEvaluationsModeRequest, selectedTeamIds: number[]): FlagEvaluationsModeBody => ({+ flag_evaluations_mode: request.mode,+ allow_downgrade: request.allowDowngrade,+ team_ids: selectedTeamIds,+ }),+ ],+ flagEvaluationsModePreviewSummary: [+ (s) => [s.flagEvaluationsModePreview],+ (preview: FlagEvaluationsModePreview | null): FlagEvaluationsModePreviewSummary | null =>+ preview && {+ organizations: preview.response.organizations,+ organizationsChanged: organizationsChangedBy(preview.response),+ organizationsLeftAboveMode: preview.response.organizations.filter(+ (organization) => organization.left_above_mode+ ).length,+ },+ ],}),listeners(({ actions, cache }) => {const onMutationSuccess = (@@ -600,6 +781,18 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(lemonToast.error('Failed to request warm-run cancellation.')actions.loadWarmRun()},+ openFlagEvaluationsModeModal: () => {+ actions.setFlagEvaluationsModeRequest(DEFAULT_FLAG_EVALUATIONS_MODE_REQUEST)+ },+ setFlagEvaluationsModeRequest: () => {+ actions.loadFlagEvaluationsModePreview()+ },+ applyFlagEvaluationsModeSuccess: ({ flagEvaluationsModeResult }) => {+ const organizations = pluralize(organizationsChangedBy(flagEvaluationsModeResult), 'organization')+ const modeLabel = FLAG_EVALUATIONS_MODE_LABELS[flagEvaluationsModeResult.flag_evaluations_mode]+ lemonToast.success(`Moved ${organizations} to ${modeLabel}.`)+ actions.loadTeamConfig()+ },}}),afterMount(({ actions }) => {diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 57fe740dcb6d..b24a515615d5 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -714,6 +714,9 @@ tools:feature-flags-staff-team-config-set-create:operation: feature_flags_staff_team_config_set_createenabled: false+ feature-flags-staff-team-config-set-flag-evaluations-mode-create:+ operation: feature_flags_staff_team_config_set_flag_evaluations_mode_create+ enabled: falsefeature-flags-staff-teams-list:operation: feature_flags_staff_teams_listenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 89748a56262b..0d8109d0af37 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -98071,6 +98071,63 @@ export namespace Schemas {not_found_cohort_ids: number[];}+ export interface StaffFlagEvaluationsModeMutation {+ /** Target flag_evaluations mode. 0 reads events, 1 reads flag_evaluations, 2 also stops writing $feature_flag_called to events. Ingestion ignores 2 until its support for 2 deploys, so 2 acts as 1 until then.+ *+ * * `0` - Events+ * * `1` - Read flag evaluations+ * * `2` - Flag evaluations only */+ flag_evaluations_mode: FlagEvaluationsModeEnum;+ /**+ * Teams whose organizations to move (max 50). The mode belongs to the organization, so the write moves every team of each organization that owns one of these teams.+ * @minItems 1+ * @maxItems 50+ */+ team_ids: number[];+ /** Also lower organizations that are above the target mode. Once ingestion acts on mode 2, lowering an organization from 2 leaves a gap in the events table for the time it spent on 2. */+ allow_downgrade?: boolean;+ /** Report what the write would change, and write nothing. */+ dry_run?: boolean;+ }++ export interface StaffOrganizationModeChange {+ /** The organization's mode before the write.+ *+ * * `0` - Events+ * * `1` - Read flag evaluations+ * * `2` - Flag evaluations only */+ current_mode: FlagEvaluationsModeEnum;+ /** The target mode.+ *+ * * `0` - Events+ * * `1` - Read flag evaluations+ * * `2` - Flag evaluations only */+ target_mode: FlagEvaluationsModeEnum;+ /** Organization id. */+ organization_id: string;+ /** Organization name. */+ organization_name: string;+ /** Teams of the organization. They all read the organization's mode. */+ team_count: number;+ /** True when the write moved the organization to the target mode, or would on a dry run. */+ changed: boolean;+ /** True when the organization is above the target mode and stays there, because allow_downgrade is not set. */+ left_above_mode: boolean;+ }++ export interface StaffFlagEvaluationsModeResponse {+ /** The target mode of the request.+ *+ * * `0` - Events+ * * `1` - Read flag evaluations+ * * `2` - Flag evaluations only */+ flag_evaluations_mode: FlagEvaluationsModeEnum;+ /** True when the request wrote nothing. */+ dry_run: boolean;+ /** One entry per organization the request covers, oldest organization first. */+ organizations: StaffOrganizationModeChange[];+ }+export interface StaffStuckCohortsResponse {/** Stuck cohorts, oldest last_calculation first (max 100). */results: StaffCohort[];@@ -107960,7 +108017,7 @@ export namespace Schemas {*/limit?: number;/**- * Search string matched against team id (exact), api_token (exact), team name (partial), or organization name (partial). Non-numeric queries must be at least 2 characters so an empty or single-letter query never returns half the table; a numeric team-id lookup is allowed at a single digit.+ * Search string matched against team id (exact), api_token (exact), team name (partial), organization name (partial), or organization id (exact). Non-numeric queries must be at least 2 characters so an empty or single-letter query never returns half the table; a numeric team-id lookup is allowed at a single digit.* @minLength 1*/search: string;