Skip to content

: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.

feat(flags): add staff toggle for minimal_flag_called_events (#69492)

Phil Haackff0cedb0ff36
diff --git a/products/feature_flags/backend/api/staff_cache.py b/products/feature_flags/backend/api/staff_cache.py
index 4ec7d2700d34..507e5a80d718 100644
--- a/products/feature_flags/backend/api/staff_cache.py
+++ b/products/feature_flags/backend/api/staff_cache.py
@@ -52,16 +52,32 @@ _READABLE_HYPERCACHES = {
READABLE_CACHE_CHOICES = list(_READABLE_HYPERCACHES)
-def _team_ids_field(help_text: str) -> serializers.ListField:
- return serializers.ListField(
- child=serializers.IntegerField(), max_length=MAX_TEAMS_PER_MUTATION, help_text=help_text
+class _RepeatedOrCommaSeparatedListField(serializers.ListField):
+ """A ListField for query params that accepts values either as repeated keys
+ (?team_ids=1&team_ids=2) or as a single comma-separated value (?team_ids=1,2). The latter is
+ how our generated TS client (and plain URLSearchParams) serializes a number[] query param, so
+ without this a caller using the generated client gets a validation error. Matches the
+ repeated-or-comma-separated handling already used for query params elsewhere, e.g. the
+ `include` param in posthog/api/element.py.
+ """
+
+ def get_value(self, dictionary: Any) -> Any:
+ value = super().get_value(dictionary)
+ if isinstance(value, list) and len(value) == 1 and isinstance(value[0], str) and "," in value[0]:
+ return value[0].split(",")
+ return value
+
+
+def _team_ids_field(help_text: str, *, max_length: int = MAX_TEAMS_PER_MUTATION) -> serializers.ListField:
+ return _RepeatedOrCommaSeparatedListField(
+ child=serializers.IntegerField(), max_length=max_length, help_text=help_text
)
class StaffCacheStatusQuerySerializer(serializers.Serializer):
team_ids = _team_ids_field(
f"Team ids to report cache status for (max {MAX_TEAMS_PER_MUTATION} per request). "
- "Repeat the param, e.g. ?team_ids=1&team_ids=2."
+ "Repeat the param (?team_ids=1&team_ids=2) or pass one comma-separated value (?team_ids=1,2)."
)
diff --git a/products/feature_flags/backend/api/staff_team_config.py b/products/feature_flags/backend/api/staff_team_config.py
new file mode 100644
index 000000000000..2156fc7207b3
--- /dev/null
+++ b/products/feature_flags/backend/api/staff_team_config.py
@@ -0,0 +1,134 @@
+import structlog
+from drf_spectacular.utils import OpenApiResponse, extend_schema_serializer
+from rest_framework import request, response, serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound
+from rest_framework.permissions import IsAuthenticated
+
+from posthog.api.mixins import validated_request
+from posthog.helpers.impersonation import is_impersonated
+from posthog.models.team import Team
+from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.permissions import IsStaffUser
+
+from products.feature_flags.backend.api.staff_cache import _team_ids_field
+from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig
+
+logger = structlog.get_logger(__name__)
+
+# A starting bound, not load-tested. Kept distinct from staff_cache.py's MAX_TEAMS_PER_MUTATION:
+# this caps a batch read, that caps a bulk mutation fan-out, and the two happen to share a
+# value today by coincidence, not by requirement.
+MAX_TEAM_IDS_PER_QUERY = 50
+
+
+class StaffTeamConfigQuerySerializer(serializers.Serializer):
+ team_ids = _team_ids_field(
+ f"Team ids to report feature-flags team config for (max {MAX_TEAM_IDS_PER_QUERY} per request). "
+ "Repeat the param (?team_ids=1&team_ids=2) or pass one comma-separated value (?team_ids=1,2).",
+ max_length=MAX_TEAM_IDS_PER_QUERY,
+ )
+
+
+class StaffTeamConfigSerializer(serializers.Serializer):
+ team_id = serializers.IntegerField(help_text="Team id.")
+ minimal_flag_called_events = serializers.BooleanField(
+ help_text=(
+ "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."
+ )
+ )
+
+
+@extend_schema_serializer(many=False)
+class StaffTeamConfigListResponseSerializer(serializers.Serializer):
+ results = StaffTeamConfigSerializer(many=True, help_text="Per-team feature-flags config.")
+
+
+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(
+ 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."
+ )
+ )
+
+
+class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):
+ """
+ Staff-only, unscoped read/write for TeamFeatureFlagsConfig (currently just
+ minimal_flag_called_events).
+
+ 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.
+
+ 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.
+ """
+
+ # Not part of the public API scope model: access is gated entirely by IsStaffUser below,
+ # not by a personal-API-key scope, so this stays out of the public OpenAPI/generated-client
+ # surface (see posthog/api/documentation.py's INTERNAL handling).
+ scope_object = "INTERNAL"
+ permission_classes = [IsAuthenticated, IsStaffUser]
+
+ @validated_request(
+ query_serializer=StaffTeamConfigQuerySerializer,
+ responses={200: OpenApiResponse(response=StaffTeamConfigListResponseSerializer)},
+ )
+ def list(self, request: request.Request, **kwargs) -> response.Response:
+ # 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"
+ )
+ )
+ 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
+ ]
+ return response.Response({"results": results})
+
+ @validated_request(
+ request_serializer=StaffTeamConfigMutationSerializer,
+ responses={200: OpenApiResponse(response=StaffTeamConfigSerializer)},
+ )
+ @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"]
+
+ team = Team.objects.filter(id=team_id).first()
+ if team is None:
+ raise NotFound(f"Team {team_id} not found.")
+
+ 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"])
+
+ # 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.
+ from posthog.tasks.team_metadata import update_team_metadata_cache_task # noqa: PLC0415
+
+ # /flags and /decide read this value out of team_metadata_hypercache, not the DB, so the
+ # write above has no effect until that cache is rebuilt.
+ update_team_metadata_cache_task.delay(team.id)
+
+ logger.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,
+ )
+
+ return response.Response({"team_id": team.id, "minimal_flag_called_events": new_value})
diff --git a/products/feature_flags/backend/models/team_feature_flags_config.py b/products/feature_flags/backend/models/team_feature_flags_config.py
index 4c9d3bd9e7f6..56dcf8a02109 100644
--- a/products/feature_flags/backend/models/team_feature_flags_config.py
+++ b/products/feature_flags/backend/models/team_feature_flags_config.py
@@ -10,10 +10,13 @@ logger = logging.getLogger(__name__)
class TeamFeatureFlagsConfig(models.Model):
"""Internal-only team-level feature flags behavior settings.
- Never expose this model through a serializer, API endpoint, or settings UI —
- it gates server-controlled behavior rollouts, not customer preferences.
- Sanctioned writers: the team-creation signal below, get_or_create_team_extension,
- and management commands.
+ 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.
+ Sanctioned writers: the team-creation signal below, get_or_create_team_extension, the
+ staff-only feature-flags-staff API (gated by IsStaffUser), and management commands.
"""
# db_constraint=False: a real FK constraint would take a SHARE ROW EXCLUSIVE
@@ -22,8 +25,9 @@ class TeamFeatureFlagsConfig(models.Model):
# Allows SDKs to send slim $feature_flag_called events for flags without a
# linked experiment. False = full events (legacy behavior). Stays False for
- # all teams, new or existing, until SDKs support the slim event shape;
- # flip via management command once they do.
+ # all teams, new or existing, until SDKs support the slim event shape; flip
+ # per-team via the feature-flags-staff API once verified, or in bulk via a
+ # management command.
minimal_flag_called_events = models.BooleanField(default=False)
diff --git a/products/feature_flags/backend/routes.py b/products/feature_flags/backend/routes.py
index 239676ab4406..c27681ab41b3 100644
--- a/products/feature_flags/backend/routes.py
+++ b/products/feature_flags/backend/routes.py
@@ -6,6 +6,7 @@ from products.feature_flags.backend.api import (
organization_feature_flag,
scheduled_change,
staff_cache,
+ staff_team_config,
staff_teams,
)
@@ -25,6 +26,11 @@ def register_routes(routers: RouterRegistry) -> None:
staff_cache.FeatureFlagsStaffCacheViewSet,
"feature_flags_staff_cache",
)
+ routers.root.register(
+ r"feature_flags_staff_team_config",
+ staff_team_config.FeatureFlagsStaffTeamConfigViewSet,
+ "feature_flags_staff_team_config",
+ )
routers.projects.register(
r"feature_flags", feature_flag.FeatureFlagViewSet, "project_feature_flags", ["project_id"]
)
diff --git a/products/feature_flags/backend/test/test_staff_cache_api.py b/products/feature_flags/backend/test/test_staff_cache_api.py
index 05b4e86b50dd..c1c0cb6668b5 100644
--- a/products/feature_flags/backend/test/test_staff_cache_api.py
+++ b/products/feature_flags/backend/test/test_staff_cache_api.py
@@ -1,10 +1,17 @@
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.http import QueryDict
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from rest_framework import status
-from products.feature_flags.backend.api.staff_cache import MAX_TEAMS_PER_MUTATION, READABLE_CACHE_CHOICES
+from products.feature_flags.backend.api.staff_cache import (
+ MAX_TEAMS_PER_MUTATION,
+ READABLE_CACHE_CHOICES,
+ StaffCacheStatusQuerySerializer,
+)
from products.feature_flags.backend.flags_cache import flags_hypercache
from products.feature_flags.backend.local_evaluation import (
flag_definitions_hypercache,
@@ -197,3 +204,21 @@ class TestFeatureFlagsStaffCacheAPI(APIBaseTest):
missing_id = self.team.id + 9999
response = self.client.get(ENTRY_URL, {"team_id": str(missing_id), "cache": "evaluation"})
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+
+class TestTeamIdsFieldQueryParamFormats(SimpleTestCase):
+ # Our generated TS client (and plain URLSearchParams) serializes a number[] query param as one
+ # comma-joined value rather than repeated keys. If `_team_ids_field` ever reverts to a plain
+ # `serializers.ListField`, the comma-separated case starts failing validation while the
+ # repeated-keys case keeps passing, silently breaking every caller that uses the generated
+ # client against a team_ids-backed query endpoint.
+ @parameterized.expand(
+ [
+ ("repeated_keys", "team_ids=1&team_ids=2"),
+ ("comma_separated", "team_ids=1,2"),
+ ]
+ )
+ def test_accepts_both_repeated_and_comma_separated_team_ids(self, _name, query_string):
+ serializer = StaffCacheStatusQuerySerializer(data=QueryDict(query_string))
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+ self.assertEqual(serializer.validated_data["team_ids"], [1, 2])
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.py
new file mode 100644
index 000000000000..625429e963b6
--- /dev/null
+++ b/products/feature_flags/backend/test/test_staff_team_config_api.py
@@ -0,0 +1,109 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.team import Team
+from 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
+
+LIST_URL = "/api/feature_flags_staff_team_config/"
+SET_URL = "/api/feature_flags_staff_team_config/set/"
+
+
+def _list_url(team_ids: list[int]) -> str:
+ query = "&".join(f"team_ids={team_id}" for team_id in team_ids)
+ return f"{LIST_URL}?{query}"
+
+
+class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+
+ def test_non_staff_user_gets_403_on_list_and_set(self):
+ self.user.is_staff = False
+ self.user.save()
+
+ list_response = self.client.get(_list_url([self.team.id]))
+ self.assertEqual(list_response.status_code, status.HTTP_403_FORBIDDEN)
+
+ set_response = self.client.post(
+ SET_URL, {"team_id": self.team.id, "minimal_flag_called_events": True}, format="json"
+ )
+ self.assertEqual(set_response.status_code, status.HTTP_403_FORBIDDEN)
+
+ 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)
+ config.minimal_flag_called_events = True
+ config.save(update_fields=["minimal_flag_called_events"])
+
+ missing_id = other_team.id + 9999
+ response = 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})
+
+ 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.
+ 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}])
+
+ def test_list_dedupes_repeated_team_ids(self):
+ response = self.client.get(_list_url([self.team.id, self.team.id]))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.json()["results"]), 1)
+
+ def test_list_over_max_team_ids_returns_400(self):
+ team_ids = list(range(1, MAX_TEAM_IDS_PER_QUERY + 2))
+ response = self.client.get(_list_url(team_ids))
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ @parameterized.expand([(True,), (False,)])
+ def test_set_updates_db_value_and_enqueues_cache_refresh_task(self, new_value):
+ with patch("posthog.tasks.team_metadata.update_team_metadata_cache_task") as mock_task:
+ response = self.client.post(
+ SET_URL, {"team_id": self.team.id, "minimal_flag_called_events": new_value}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"team_id": self.team.id, "minimal_flag_called_events": new_value})
+
+ config = TeamFeatureFlagsConfig.objects.get(team=self.team)
+ self.assertEqual(config.minimal_flag_called_events, new_value)
+ # /flags and /decide read this value out of team_metadata_hypercache, not the DB, so a
+ # bare write has no effect until that cache is rebuilt.
+ mock_task.delay.assert_called_once_with(self.team.id)
+
+ def test_set_returns_404_for_unknown_team(self):
+ missing_id = self.team.id + 9999
+ response = self.client.post(SET_URL, {"team_id": missing_id, "minimal_flag_called_events": True}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_set_creates_config_row_if_missing(self):
+ # Exercises the get_or_create_team_extension create branch: don't rely on the
+ # auto-created row from the team-creation signal.
+ TeamFeatureFlagsConfig.objects.filter(team=self.team).delete()
+
+ with patch("posthog.tasks.team_metadata.update_team_metadata_cache_task"):
+ response = self.client.post(
+ SET_URL, {"team_id": self.team.id, "minimal_flag_called_events": True}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ config = TeamFeatureFlagsConfig.objects.get(team=self.team)
+ self.assertTrue(config.minimal_flag_called_events)
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 5b581e306c17..c3355d324de8 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -115,6 +115,25 @@ export interface StaffCacheEntryResponseApi {
data: StaffCacheEntryResponseApiData
}
+export interface StaffTeamConfigApi {
+ /** Team id. */
+ 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
+}
+
+export interface StaffTeamConfigListResponseApi {
+ /** Per-team feature-flags config. */
+ results: StaffTeamConfigApi[]
+}
+
+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
+}
+
export interface StaffTeamResultApi {
/** Team id. */
id: number
@@ -1564,7 +1583,7 @@ export interface PatchedScheduledChangeApi {
export type FeatureFlagsStaffCacheListParams = {
/**
- * Team ids to report cache status for (max 50 per request). Repeat the param, e.g. ?team_ids=1&team_ids=2.
+ * Team ids to report cache status for (max 50 per request). Repeat the param (?team_ids=1&team_ids=2) or pass one comma-separated value (?team_ids=1,2).
* @maxItems 50
*/
team_ids: number[]
@@ -1595,6 +1614,14 @@ export const FeatureFlagsStaffCacheEntryRetrieveCache = {
DefinitionsNoCohorts: 'definitions_no_cohorts',
} as const
+export type FeatureFlagsStaffTeamConfigListParams = {
+ /**
+ * Team ids to report feature-flags team config for (max 50 per request). Repeat the param (?team_ids=1&team_ids=2) or pass one comma-separated value (?team_ids=1,2).
+ * @maxItems 50
+ */
+ team_ids: number[]
+}
+
export type FeatureFlagsStaffTeamsListParams = {
/**
* Maximum number of teams to return (default 25, max 100).
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index ed58be16ec44..4bc89eb9b70b 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -35,6 +35,7 @@ import type {
FeatureFlagsMyFlagsRetrieveParams,
FeatureFlagsStaffCacheEntryRetrieveParams,
FeatureFlagsStaffCacheListParams,
+ FeatureFlagsStaffTeamConfigListParams,
FeatureFlagsStaffTeamsListParams,
FlagValueResponseApi,
FlagValueValuesRetrieveParams,
@@ -52,6 +53,9 @@ import type {
StaffCacheMutationApi,
StaffCacheMutationResponseApi,
StaffCacheStatusResponseApi,
+ StaffTeamConfigApi,
+ StaffTeamConfigListResponseApi,
+ StaffTeamConfigMutationApi,
StaffTeamSearchResponseApi,
UserBlastRadiusRequestApi,
UserBlastRadiusResponseApi,
@@ -206,6 +210,70 @@ export const featureFlagsStaffCacheRebuildCreate = async (
})
}
+export const getFeatureFlagsStaffTeamConfigListUrl = (params: FeatureFlagsStaffTeamConfigListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/feature_flags_staff_team_config/?${stringifiedParams}`
+ : `/api/feature_flags_staff_team_config/`
+}
+
+/**
+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig (currently just
+ * minimal_flag_called_events).
+ *
+ * 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.
+ *
+ * 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 featureFlagsStaffTeamConfigList = async (
+ params: FeatureFlagsStaffTeamConfigListParams,
+ options?: RequestInit
+): Promise<StaffTeamConfigListResponseApi> => {
+ return apiMutator<StaffTeamConfigListResponseApi>(getFeatureFlagsStaffTeamConfigListUrl(params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getFeatureFlagsStaffTeamConfigSetCreateUrl = () => {
+ return `/api/feature_flags_staff_team_config/set/`
+}
+
+/**
+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig (currently just
+ * minimal_flag_called_events).
+ *
+ * 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.
+ *
+ * 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 featureFlagsStaffTeamConfigSetCreate = async (
+ staffTeamConfigMutationApi: StaffTeamConfigMutationApi,
+ options?: RequestInit
+): Promise<StaffTeamConfigApi> => {
+ return apiMutator<StaffTeamConfigApi>(getFeatureFlagsStaffTeamConfigSetCreateUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(staffTeamConfigMutationApi),
+ })
+}
+
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.ts
index 515b98cde919..26457d2756c6 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -71,6 +71,26 @@ export const FeatureFlagsStaffCacheRebuildCreateBody = /* @__PURE__ */ zod.objec
),
})
+/**
+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig (currently just
+ * minimal_flag_called_events).
+ *
+ * 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.
+ *
+ * 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 FeatureFlagsStaffTeamConfigSetCreateBody = /* @__PURE__ */ zod.object({
+ team_id: zod.number().describe('Team id to update. Exactly one team per request.'),
+ minimal_flag_called_events: zod
+ .boolean()
+ .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."
+ ),
+})
+
export const featureFlagsCopyFlagsCreateBodyTargetProjectIdsMax = 50
export const featureFlagsCopyFlagsCreateBodyCopyScheduleDefault = false
diff --git a/products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene.tsx b/products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene.tsx
index f54e8866d7f5..3a3dd5933397 100644
--- a/products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene.tsx
+++ b/products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene.tsx
@@ -29,7 +29,7 @@ export function FeatureFlagsStaffToolsScene(): JSX.Element {
<SceneContent>
<SceneTitleSection
name="Flags staff tools"
- description="Look up any team across all organizations to inspect and rebuild its flag caches."
+ description="Look up any team across all organizations to inspect and rebuild its flag caches, or adjust its feature-flags config."
resourceType={{ type: 'feature_flag' }}
actions={
<LemonButton type="secondary" size="small" to={urls.instanceSettings()}>
diff --git a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
index 2b5404e67b0b..b68ec837cb20 100644
--- a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
+++ b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconEye } from '@posthog/icons'
-import { LemonButton, LemonDialog, LemonTable, LemonTableColumns, LemonTag } from '@posthog/lemon-ui'
+import { LemonButton, LemonDialog, LemonSwitch, LemonTable, LemonTableColumns, LemonTag } from '@posthog/lemon-ui'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { truncate } from 'lib/utils/strings'
@@ -50,8 +50,11 @@ export function StaffCacheToolsTab(): JSX.Element {
cacheStatusLoading,
rebuildResultLoading,
clearResultLoading,
+ teamConfigByTeamId,
+ pendingTeamConfigTeamIds,
} = useValues(featureFlagsStaffToolsLogic)
- const { rebuildCache, clearCache, loadCacheStatus, viewCacheEntry } = useActions(featureFlagsStaffToolsLogic)
+ const { rebuildCache, clearCache, loadCacheStatus, viewCacheEntry, setMinimalFlagCalledEvents } =
+ useActions(featureFlagsStaffToolsLogic)
const hasSelection = selectedTeamIds.length > 0
const mutating = rebuildResultLoading || clearResultLoading
@@ -86,6 +89,23 @@ export function StaffCacheToolsTab(): JSX.Element {
</CopyToClipboardInline>
),
},
+ {
+ title: 'Minimal flag_called events',
+ key: 'minimal_flag_called_events',
+ render: (_, team) => {
+ const config = teamConfigByTeamId[team.id]
+ const pending = pendingTeamConfigTeamIds.includes(team.id)
+ return (
+ <LemonSwitch
+ checked={config?.minimal_flag_called_events ?? false}
+ onChange={(checked) => setMinimalFlagCalledEvents(team.id, checked)}
+ loading={pending}
+ disabledReason={pending ? 'Update in progress' : !config ? 'Loading current value…' : undefined}
+ data-attr="ff-staff-team-config-minimal-flag-called-events"
+ />
+ )
+ },
+ },
...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.ts
index 6f343199ef2f..f0280bafcc58 100644
--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
@@ -210,4 +210,88 @@ describe('featureFlagsStaffToolsLogic', () => {
.toMatchValues({ teamSearchResults: [TEAM], knownTeams: { 5: TEAM } })
})
})
+
+ describe('team config', () => {
+ const TEAM_CONFIG_URL = '/api/feature_flags_staff_team_config'
+ const SET_URL = '/api/feature_flags_staff_team_config/set'
+
+ it('loads team config alongside cache status when the team selection changes', async () => {
+ useMocks({
+ get: { [TEAM_CONFIG_URL]: { results: [{ team_id: 5, minimal_flag_called_events: true }] } },
+ })
+
+ logic.actions.setSelectedTeamIds([5])
+ await expectLogic(logic).toDispatchActionsInAnyOrder([
+ 'loadCacheStatus',
+ 'loadTeamConfig',
+ 'loadTeamConfigSuccess',
+ ])
+ await expectLogic(logic).toMatchValues({
+ teamConfigByTeamId: { 5: { team_id: 5, minimal_flag_called_events: true } },
+ })
+ })
+
+ it('setMinimalFlagCalledEvents updates teamConfigByTeamId and shows a success toast', async () => {
+ useMocks({
+ get: { [TEAM_CONFIG_URL]: { results: [{ team_id: 5, minimal_flag_called_events: false }] } },
+ post: { [SET_URL]: { team_id: 5, minimal_flag_called_events: true } },
+ })
+
+ // The switch only renders once its row has loaded, so seed the selection first —
+ // the mutation reducer patches an existing row in place, it doesn't add a new one.
+ logic.actions.setSelectedTeamIds([5])
+ await expectLogic(logic).toDispatchActions(['loadTeamConfigSuccess'])
+
+ logic.actions.setMinimalFlagCalledEvents(5, true)
+ // setMinimalFlagCalledEvents is a plain listener (not kea-loaders), since the
+ // auto-generated Failure action wouldn't carry the team_id needed to clear the
+ // right row's pending state on failure. teamConfigMutationSucceeded/Settled are the
+ // actions it dispatches instead of the usual Success/Failure pair.
+ await expectLogic(logic).toDispatchActions(['teamConfigMutationSucceeded', 'teamConfigMutationSettled'])
+
+ expect(lemonToast.success).toHaveBeenCalled()
+ await expectLogic(logic).toMatchValues({
+ pendingTeamConfigTeamIds: [],
+ teamConfigByTeamId: { 5: { team_id: 5, minimal_flag_called_events: true } },
+ })
+ })
+
+ it('shows an error toast and leaves the value unchanged on failure', async () => {
+ useMocks({
+ get: { [TEAM_CONFIG_URL]: { results: [{ team_id: 5, minimal_flag_called_events: false }] } },
+ post: { [SET_URL]: () => [500, {}] },
+ })
+
+ // Seed a known-good value first so a no-op failure is verifiably "unchanged", not just
+ // absent. loadTeamConfig() alone would no-op: the loader bails out when
+ // selectedTeamIds is empty, so the selection must be set first.
+ logic.actions.setSelectedTeamIds([5])
+ await expectLogic(logic).toDispatchActions(['loadTeamConfigSuccess'])
+
+ logic.actions.setMinimalFlagCalledEvents(5, true)
+ // No teamConfigMutationSucceeded on failure — only the settle action fires, clearing
+ // the pending row.
+ await expectLogic(logic).toDispatchActions(['teamConfigMutationSettled'])
+
+ expect(lemonToast.error).toHaveBeenCalled()
+ await expectLogic(logic).toMatchValues({
+ pendingTeamConfigTeamIds: [],
+ teamConfigByTeamId: { 5: { team_id: 5, minimal_flag_called_events: false } },
+ })
+ })
+
+ 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 } })
+
+ // Both dispatches happen before either mocked request resolves, exercising the
+ // double-submit guard rather than two sequential, already-settled calls.
+ await expectLogic(logic, () => {
+ logic.actions.setMinimalFlagCalledEvents(5, true)
+ logic.actions.setMinimalFlagCalledEvents(5, true)
+ }).toFinishAllListeners()
+
+ expect(handleSet).toHaveBeenCalledTimes(1)
+ })
+ })
})
diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
index c0ff2203cfe3..84288bc42d0b 100644
--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
@@ -2,14 +2,15 @@ import { actions, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
-import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { toParams } from 'lib/utils/url'
import {
featureFlagsStaffCacheClearCreate,
featureFlagsStaffCacheEntryRetrieve,
+ featureFlagsStaffCacheList,
featureFlagsStaffCacheRebuildCreate,
+ featureFlagsStaffTeamConfigList,
+ featureFlagsStaffTeamConfigSetCreate,
featureFlagsStaffTeamsList,
} from '../generated/api'
import type {
@@ -18,6 +19,7 @@ import type {
StaffCacheEntryResponseApi,
StaffCacheMutationResponseApi,
StaffCacheTeamStatusApi,
+ StaffTeamConfigApi,
StaffTeamResultApi,
} from '../generated/api.schemas'
import type { featureFlagsStaffToolsLogicType } from './featureFlagsStaffToolsLogicType'
@@ -38,13 +40,13 @@ export const CACHE_LABELS: Record<StaffReadableCacheKind, string> = {
const MIN_SEARCH_LENGTH = 2
const SEARCH_DEBOUNCE_MS = 300
-const STAFF_CACHE_URL = 'api/feature_flags_staff_cache'
export type StaffTeamResult = StaffTeamResultApi
export type StaffCacheTeamStatus = StaffCacheTeamStatusApi
export type StaffCacheEntryStatus = StaffCacheTeamStatusApi['evaluation']
export type StaffCacheMutationResponse = StaffCacheMutationResponseApi
export type StaffCacheEntry = StaffCacheEntryResponseApi
+export type StaffTeamConfig = StaffTeamConfigApi
export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>([
path(['products', 'feature_flags', 'frontend', 'staff', 'featureFlagsStaffToolsLogic']),
@@ -52,6 +54,12 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(
setSelectedTeamIds: (teamIds: number[]) => ({ teamIds }),
seedTeamFromDeepLink: (teamId: number) => ({ teamId }),
closeCacheEntryModal: true,
+ setMinimalFlagCalledEvents: (teamId: number, minimalFlagCalledEvents: boolean) => ({
+ teamId,
+ minimalFlagCalledEvents,
+ }),
+ teamConfigMutationSucceeded: (teamConfig: StaffTeamConfig) => ({ teamConfig }),
+ teamConfigMutationSettled: (teamId: number) => ({ teamId }),
}),
loaders(({ values }) => ({
teamSearchResults: [
@@ -84,13 +92,7 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(
// fetch of the final selection instead of refetching the growing selection on
// every single add (matches the searchTeams debounce pattern above).
await breakpoint(SEARCH_DEBOUNCE_MS)
- // team_ids is a repeated-key query param (?team_ids=1&team_ids=2); the generated
- // client serializes array params as a single comma-joined value, which this
- // ListField-backed endpoint can't parse.
- // nosemgrep: prefer-codegen-api
- const response = await api.get<{ results: StaffCacheTeamStatus[] }>(
- `${STAFF_CACHE_URL}?${toParams({ team_ids: teamIds }, true)}`
- )
+ const response = await featureFlagsStaffCacheList({ team_ids: teamIds })
breakpoint()
return response.results
},
@@ -120,6 +122,23 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(
},
},
],
+ teamConfig: [
+ [] as StaffTeamConfig[],
+ {
+ loadTeamConfig: async (_: void, breakpoint) => {
+ const teamIds = values.selectedTeamIds
+ if (teamIds.length === 0) {
+ return []
+ }
+ // Debounce for the same reason as cacheStatus above: collapse rapid
+ // selection changes into one fetch of the final selection.
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ const response = await featureFlagsStaffTeamConfigList({ team_ids: teamIds })
+ breakpoint()
+ return response.results
+ },
+ },
+ ],
})),
reducers({
selectedTeamIds: [
@@ -156,6 +175,25 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(
closeCacheEntryModal: () => null,
},
],
+ // 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.
+ teamConfig: [
+ [] as StaffTeamConfig[],
+ {
+ teamConfigMutationSucceeded: (state, { teamConfig }) =>
+ state.map((config) => (config.team_id === teamConfig.team_id ? teamConfig : config)),
+ },
+ ],
+ // Reactive per-row in-flight flag for the switch's `loading`/`disabledReason` props.
+ pendingTeamConfigTeamIds: [
+ [] as number[],
+ {
+ setMinimalFlagCalledEvents: (state, { teamId }) =>
+ state.includes(teamId) ? state : [...state, teamId],
+ teamConfigMutationSettled: (state, { teamId }) => state.filter((id) => id !== teamId),
+ },
+ ],
}),
selectors({
selectedTeams: [
@@ -168,8 +206,13 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(
(cacheStatus: StaffCacheTeamStatus[]): Record<number, StaffCacheTeamStatus> =>
Object.fromEntries(cacheStatus.map((status) => [status.team_id, status])),
],
+ teamConfigByTeamId: [
+ (s) => [s.teamConfig],
+ (teamConfig: StaffTeamConfig[]): Record<number, StaffTeamConfig> =>
+ Object.fromEntries(teamConfig.map((config) => [config.team_id, config])),
+ ],
}),
- listeners(({ actions }) => {
+ listeners(({ actions, cache }) => {
const onMutationSuccess = (
result: StaffCacheMutationResponse | null,
doneMessage: string,
@@ -187,10 +230,12 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(
return {
setSelectedTeamIds: () => {
actions.loadCacheStatus()
+ actions.loadTeamConfig()
},
seedTeamFromDeepLink: ({ teamId }) => {
actions.searchTeams({ query: String(teamId) })
actions.loadCacheStatus()
+ actions.loadTeamConfig()
},
rebuildCacheSuccess: ({ rebuildResult }) => {
onMutationSuccess(
@@ -212,6 +257,30 @@ 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)
+ }
+ },
}
}),
urlToAction(({ actions, values }) => ({
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index c4c4198afc52..5d0f06dfa2a5 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -285,6 +285,12 @@ tools:
feature-flags-staff-cache-rebuild-create:
operation: feature_flags_staff_cache_rebuild_create
enabled: false
+ feature-flags-staff-team-config-list:
+ operation: feature_flags_staff_team_config_list
+ enabled: false
+ feature-flags-staff-team-config-set-create:
+ operation: feature_flags_staff_team_config_set_create
+ enabled: false
feature-flags-staff-teams-list:
operation: feature_flags_staff_teams_list
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 92c0dee60f44..50df797a19a4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55906,6 +55906,25 @@ export namespace Schemas {
results: StaffCacheTeamStatus[];
}
+ export interface StaffTeamConfig {
+ /** Team id. */
+ 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;
+ }
+
+ export interface StaffTeamConfigListResponse {
+ /** Per-team feature-flags config. */
+ results: StaffTeamConfig[];
+ }
+
+ 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;
+ }
+
export interface StaffTeamResult {
/** Team id. */
id: number;
@@ -65680,7 +65699,7 @@ export namespace Schemas {
export type FeatureFlagsStaffCacheListParams = {
/**
- * Team ids to report cache status for (max 50 per request). Repeat the param, e.g. ?team_ids=1&team_ids=2.
+ * Team ids to report cache status for (max 50 per request). Repeat the param (?team_ids=1&team_ids=2) or pass one comma-separated value (?team_ids=1,2).
* @maxItems 50
*/
team_ids: number[];
@@ -65711,6 +65730,14 @@ export namespace Schemas {
DefinitionsNoCohorts: 'definitions_no_cohorts',
} as const;
+ export type FeatureFlagsStaffTeamConfigListParams = {
+ /**
+ * Team ids to report feature-flags team config for (max 50 per request). Repeat the param (?team_ids=1&team_ids=2) or pass one comma-separated value (?team_ids=1,2).
+ * @maxItems 50
+ */
+ team_ids: number[];
+ };
+
export type FeatureFlagsStaffTeamsListParams = {
/**
* Maximum number of teams to return (default 25, max 100).