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 tools to inspect and manage flag caches (#69053)

Phil Haackcf7623543b8e
diff --git a/frontend/src/lib/components/Account/AccountMenu.tsx b/frontend/src/lib/components/Account/AccountMenu.tsx
index ad59212ef0ff..ea16ea942df4 100644
--- a/frontend/src/lib/components/Account/AccountMenu.tsx
+++ b/frontend/src/lib/components/Account/AccountMenu.tsx
@@ -19,6 +19,7 @@ import {
IconReceipt,
IconServer,
IconShieldLock,
+ IconToggle,
} from '@posthog/icons'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -424,6 +425,18 @@ export function AccountMenu({ trigger, ...props }: AccountMenuProps): JSX.Elemen
Instance panel
</Link>
</DropdownMenuItem>
+ <DropdownMenuItem asChild>
+ <Link
+ to={urls.featureFlagsStaffTools()}
+ buttonProps={{
+ menuItem: true,
+ }}
+ data-attr="top-menu-flags-staff-tools"
+ >
+ <IconToggle />
+ Flags staff tools
+ </Link>
+ </DropdownMenuItem>
{user?.is_impersonated ||
preflight?.is_debug ||
diff --git a/frontend/src/lib/components/Account/NewAccountMenu.tsx b/frontend/src/lib/components/Account/NewAccountMenu.tsx
index 2d3ede1facef..29f31ed4cc6b 100644
--- a/frontend/src/lib/components/Account/NewAccountMenu.tsx
+++ b/frontend/src/lib/components/Account/NewAccountMenu.tsx
@@ -9,6 +9,7 @@ import {
IconReceipt,
IconServer,
IconShieldLock,
+ IconToggle,
} from '@posthog/icons'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -383,6 +384,21 @@ export function NewAccountMenu({ isLayoutNavCollapsed }: AccountMenuProps): JSX.
</Link>
)}
/>
+ <Menu.Item
+ render={(props) => (
+ <Link
+ {...props}
+ to={urls.featureFlagsStaffTools()}
+ buttonProps={{
+ menuItem: true,
+ }}
+ data-attr="new-account-menu-flags-staff-tools"
+ >
+ <IconToggle />
+ Flags staff tools
+ </Link>
+ )}
+ />
<Menu.Item
render={(props) => (
<Link
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 5fe35028da1f..7779d4d8c876 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -122,6 +122,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
ErrorTrackingIssueFingerprints: () =>
import('../../products/error_tracking/frontend/scenes/ErrorTrackingFingerprintsScene/ErrorTrackingIssueFingerprintsScene'),
FeatureFlagTemplates: () => import('../../products/feature_flags/frontend/FeatureFlagTemplatesScene'),
+ FeatureFlagsStaffTools: () => import('../../products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene'),
Game368Hedgehogs: () => import('../../products/games/368Hedgehogs/368Hedgehogs'),
FlappyHog: () => import('../../products/games/FlappyHog/FlappyHog'),
IdentityMatching: () => import('../../products/growth/frontend/IdentityMatchingScene'),
@@ -269,6 +270,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/error_tracking/alerts/:id': ['HogFunction', 'errorTrackingAlert'],
'/error_tracking/alerts/new/:templateId': ['HogFunction', 'errorTrackingAlertNew'],
'/feature_flags/templates': ['FeatureFlagTemplates', 'featureFlagTemplates'],
+ '/feature_flags/staff': ['FeatureFlagsStaffTools', 'featureFlagsStaffTools'],
'/games/368hedgehogs': ['Game368Hedgehogs', 'game368Hedgehogs'],
'/games/flappyhog': ['FlappyHog', 'flappyHog'],
'/identity-matching': ['IdentityMatching', 'identityMatching'],
@@ -713,6 +715,7 @@ export const productConfiguration: Record<string, any> = {
ErrorTrackingIssue: { projectBased: true, name: 'Error tracking issue', layout: 'app-raw' },
ErrorTrackingIssueFingerprints: { projectBased: true, name: 'Error tracking issue fingerprints' },
FeatureFlagTemplates: { projectBased: true, name: 'Feature flag templates' },
+ FeatureFlagsStaffTools: { instanceLevel: true, name: 'Flags staff tools' },
Game368Hedgehogs: { name: '368Hedgehogs', projectBased: true, activityScope: 'Games' },
FlappyHog: { name: 'FlappyHog', projectBased: true, activityScope: 'Games' },
IdentityMatching: {
@@ -1147,6 +1150,7 @@ export const productUrls = {
featureFlag: (id: string | number): string => `/feature_flags/${id}`,
featureFlags: (tab?: string): string => `/feature_flags${tab ? `?tab=${tab}` : ''}`,
featureFlagTemplates: (): string => '/feature_flags/templates',
+ featureFlagsStaffTools: (teamId?: number): string => `/feature_flags/staff${teamId ? `?team_id=${teamId}` : ''}`,
featureFlagNew: ({
type,
sourceId,
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index 2ffdde0354d5..7d46fe8fd56e 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -855,6 +855,7 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.sqlEditor()]: [Scene.SQLEditor, 'sqlEditor'],
[urls.featureFlags()]: [Scene.FeatureFlags, 'featureFlags'],
[urls.featureFlagTemplates()]: ['FeatureFlagTemplates' as Scene, 'featureFlagTemplates'],
+ [urls.featureFlagsStaffTools()]: ['FeatureFlagsStaffTools' as Scene, 'featureFlagsStaffTools'],
[urls.featureFlag(':id')]: [Scene.FeatureFlag, 'featureFlag'],
[urls.annotations()]: [Scene.DataManagement, 'annotations'],
[urls.annotation(':id')]: [Scene.DataManagement, 'annotation'],
diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.py
index 1198e6d7281a..2d50d5f0cd4c 100644
--- a/posthog/admin/admins/team_admin.py
+++ b/posthog/admin/admins/team_admin.py
@@ -144,6 +144,7 @@ class TeamAdmin(admin.ModelAdmin):
"updated_at",
"internal_properties",
"remote_config_cache_actions",
+ "flags_staff_tools_link",
"delete_recordings",
"api_token_display",
"admit_state",
@@ -178,6 +179,7 @@ class TeamAdmin(admin.ModelAdmin):
"project",
"internal_properties",
"remote_config_cache_actions",
+ "flags_staff_tools_link",
],
},
),
@@ -523,6 +525,16 @@ class TeamAdmin(admin.ModelAdmin):
delete_url,
)
+ @admin.display(description="Flags staff tools")
+ def flags_staff_tools_link(self, team: Team):
+ # Mirrors urls.featureFlagsStaffTools() in products/feature_flags/manifest.tsx; keep in sync.
+ if not team.pk:
+ return "-"
+ return format_html(
+ '<a class="button" href="/feature_flags/staff?team_id={}" target="_blank" rel="noopener noreferrer">Open flags staff tools</a>',
+ team.pk,
+ )
+
@admin.display(description="Remote config cache actions")
def remote_config_cache_actions(self, team: Team):
if not team.pk:
diff --git a/posthog/admin/inlines/team_inline.py b/posthog/admin/inlines/team_inline.py
index 35f5a97f416e..f56d55b13e11 100644
--- a/posthog/admin/inlines/team_inline.py
+++ b/posthog/admin/inlines/team_inline.py
@@ -44,6 +44,7 @@ class TeamInline(TabularInlinePaginated):
"internal_properties",
"delete_recordings",
"remote_config_cache_actions",
+ "flags_staff_tools_link",
"api_token_display",
"admit_state",
"ai_gateway_actions",
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 04c1b6b9c9f9..ec52ad1f0a68 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -710,6 +710,10 @@ SPECTACULAR_SETTINGS = {
"RuntimeAdapterEnum": ["claude", "codex"],
"ClaudeRuntimeAdapterEnum": ["claude"],
"CodexRuntimeAdapterEnum": ["codex"],
+ # StaffCacheEntryResponse.source and StaffCacheEntryStatus.source share the same
+ # redis/miss choice set. Pin to a stable name so the collision doesn't auto-resolve
+ # to a hash name.
+ "StaffCacheSourceEnum": ["redis", "miss"],
},
}
diff --git a/products/feature_flags/backend/api/staff_cache.py b/products/feature_flags/backend/api/staff_cache.py
new file mode 100644
index 000000000000..4ec7d2700d34
--- /dev/null
+++ b/products/feature_flags/backend/api/staff_cache.py
@@ -0,0 +1,318 @@
+from collections.abc import Callable
+from typing import Any
+
+import structlog
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiResponse, extend_schema_field, extend_schema_serializer
+from rest_framework import request, response, serializers, status, 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.permissions import IsStaffUser
+
+from products.feature_flags.backend.flags_cache import enqueue_evaluation_cache_invalidation, flags_hypercache
+from products.feature_flags.backend.local_evaluation import (
+ flag_definitions_hypercache,
+ flag_definitions_without_cohorts_hypercache,
+)
+from products.feature_flags.backend.tasks import (
+ clear_team_definitions_cache,
+ clear_team_evaluation_cache,
+ update_team_flags_cache,
+)
+
+logger = structlog.get_logger(__name__)
+
+# A starting bound, not load-tested. Rebuild/clear act on every listed team, so this caps how
+# much work a single staff request can trigger; adjust if it proves too tight.
+MAX_TEAMS_PER_MUTATION = 50
+
+EVALUATION = "evaluation"
+DEFINITIONS = "definitions"
+DEFINITIONS_NO_COHORTS = "definitions_no_cohorts"
+
+# What rebuild/clear act on. "definitions" already rebuilds/clears both definitions-cache
+# variants together (see update_flag_caches / clear_flag_definition_caches), so there is no
+# separate mutation target for the no-cohorts variant.
+CACHE_CHOICES = [EVALUATION, DEFINITIONS]
+
+# The readable caches, enumerated once here rather than hardcoded in list/entry.
+_READABLE_HYPERCACHES = {
+ EVALUATION: flags_hypercache,
+ DEFINITIONS: flag_definitions_hypercache,
+ DEFINITIONS_NO_COHORTS: flag_definitions_without_cohorts_hypercache,
+}
+
+# What status/entry can read. Unlike mutation, status/entry read each definitions-cache
+# variant independently, so the no-cohorts variant is separately observable here.
+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 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."
+ )
+
+
+def _cache_source_field() -> serializers.ChoiceField:
+ return serializers.ChoiceField(
+ choices=["redis", "miss"],
+ help_text="'redis' when a warm entry is cached, or 'miss' when nothing is cached in Redis.",
+ )
+
+
+class StaffCacheEntryStatusSerializer(serializers.Serializer):
+ source = _cache_source_field() # type: ignore[assignment]
+ flag_count = serializers.IntegerField(
+ allow_null=True,
+ help_text="Number of flags in the cached payload, or null on a miss.",
+ )
+
+
+class StaffCacheTeamStatusSerializer(serializers.Serializer):
+ team_id = serializers.IntegerField(help_text="Team id.")
+ evaluation = StaffCacheEntryStatusSerializer(help_text="Status of the /flags evaluation cache.")
+ definitions = StaffCacheEntryStatusSerializer(
+ help_text="Status of the /flags/definitions local-eval cache (with-cohorts variant)."
+ )
+ definitions_no_cohorts = StaffCacheEntryStatusSerializer(
+ help_text=(
+ "Status of the /flags/definitions local-eval cache (without-cohorts variant, cohort "
+ "filters transformed to properties for simple SDK clients)."
+ )
+ )
+
+
+@extend_schema_serializer(many=False)
+class StaffCacheStatusResponseSerializer(serializers.Serializer):
+ results = StaffCacheTeamStatusSerializer(many=True, help_text="Per-team cache status.")
+
+
+class StaffCacheMutationSerializer(serializers.Serializer):
+ team_ids = _team_ids_field(f"Team ids to act on (max {MAX_TEAMS_PER_MUTATION} per request).")
+ caches = serializers.ListField(
+ child=serializers.ChoiceField(choices=CACHE_CHOICES),
+ required=False,
+ default=CACHE_CHOICES,
+ help_text=(
+ "Which logical caches to act on: 'evaluation' (the /flags cache) and/or 'definitions' "
+ "(the /flags/definitions local-eval cache). Defaults to both."
+ ),
+ )
+
+
+class StaffCacheMutationResponseSerializer(serializers.Serializer):
+ queued_team_ids = serializers.ListField(
+ child=serializers.IntegerField(),
+ help_text="Team ids for which the requested action's tasks were enqueued.",
+ )
+ not_found_team_ids = serializers.ListField(
+ child=serializers.IntegerField(),
+ help_text="Requested team ids that do not exist.",
+ )
+
+
+class StaffCacheEntryQuerySerializer(serializers.Serializer):
+ team_id = serializers.IntegerField(help_text="Team id to fetch the cache entry for.")
+ cache = serializers.ChoiceField(
+ choices=READABLE_CACHE_CHOICES,
+ help_text=(
+ "Which cache to fetch: 'evaluation' (the /flags cache), 'definitions' (the "
+ "/flags/definitions local-eval cache, with-cohorts variant), or 'definitions_no_cohorts' "
+ "(the without-cohorts variant served to simple SDK clients)."
+ ),
+ )
+
+
+@extend_schema_field(OpenApiTypes.OBJECT)
+class StaffCacheEntryDataField(serializers.JSONField):
+ """Raw cache payload; shape mirrors the /flags or /flags/definitions response for the team."""
+
+
+class StaffCacheEntryResponseSerializer(serializers.Serializer):
+ team_id = serializers.IntegerField(help_text="Team id.")
+ cache = serializers.ChoiceField(choices=READABLE_CACHE_CHOICES, help_text="Which cache this entry is for.")
+ source = _cache_source_field() # type: ignore[assignment]
+ data = StaffCacheEntryDataField( # type: ignore[assignment]
+ allow_null=True,
+ help_text="Raw cached payload as stored in Redis, or null on a miss.",
+ )
+
+
+def _entry_status(entry: tuple[dict | None, str, str | None]) -> dict[str, Any]:
+ """Turn a batch_get_from_cache tuple into the reported {source, flag_count}.
+
+ Status is read Redis-only via batch_get_from_cache (the same side-effect-free read the
+ verifiers use): a plain get_from_cache_with_source would trigger a live DB rebuild as a side
+ effect of merely viewing status, repopulating the very cache the staff member is inspecting and
+ making "miss" unobservable. Redis is the hot path the flags service actually reads, so "warm in
+ redis" is the meaningful signal. A redis hit whose stored payload is empty yields data None;
+ report that as a miss too since there are no flags to count.
+ """
+ data, source, _etag = entry
+ if data is None:
+ return {"source": "miss", "flag_count": None}
+ return {"source": source, "flag_count": len(data.get("flags", []))}
+
+
+def _dispatch_mutation(
+ request: request.Request,
+ team_ids: list[int],
+ caches: list[str],
+ *,
+ evaluation_fn: Callable[[int], None],
+ definitions_fn: Callable[[int], None],
+ log_event: str,
+) -> response.Response:
+ """Shared shape of `rebuild` and `clear`: split team_ids into found/not-found, dispatch the
+ per-cache action for each found team, log, and return the 202 response both actions share."""
+ # Dedupe (preserving order) so a caller passing the same id twice doesn't enqueue duplicate
+ # rebuild/clear work for that team.
+ deduped_ids = list(dict.fromkeys(team_ids))
+ found_set = set(Team.objects.filter(id__in=deduped_ids).values_list("id", flat=True))
+ found_ids = [team_id for team_id in deduped_ids if team_id in found_set]
+ not_found_ids = [team_id for team_id in deduped_ids if team_id not in found_set]
+
+ for team_id in found_ids:
+ if EVALUATION in caches:
+ evaluation_fn(team_id)
+ if DEFINITIONS in caches:
+ definitions_fn(team_id)
+
+ logger.info(
+ log_event,
+ staff_user_id=request.user.id,
+ was_impersonated=is_impersonated(request),
+ team_ids=found_ids,
+ not_found_team_ids=not_found_ids,
+ caches=caches,
+ )
+
+ return response.Response(
+ {"queued_team_ids": found_ids, "not_found_team_ids": not_found_ids},
+ status=status.HTTP_202_ACCEPTED,
+ )
+
+
+class FeatureFlagsStaffCacheViewSet(viewsets.ViewSet):
+ """
+ Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
+
+ Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
+ or clears both definitions-cache variants together). Status/entry can read a third, narrower
+ target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
+ individually readable even though they're only mutated as a pair.
+
+ Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
+ when a flag changes) rather than re-implementing cache-write logic. Registered on the root
+ router so it is not team-nested; staff act on teams they do not belong to.
+ """
+
+ # 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=StaffCacheStatusQuerySerializer,
+ responses={200: OpenApiResponse(response=StaffCacheStatusResponseSerializer)},
+ )
+ 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 _dispatch_mutation's handling of team_ids below.
+ team_ids: list[int] = list(dict.fromkeys(request.validated_query_data["team_ids"]))
+ teams_by_id = {team.id: team for team in Team.objects.filter(id__in=team_ids)}
+ teams = [teams_by_id[team_id] for team_id in team_ids if team_id in teams_by_id]
+
+ # One Redis MGET per cache across all teams, rather than one per (team, cache).
+ batches = {kind: hypercache.batch_get_from_cache(teams) for kind, hypercache in _READABLE_HYPERCACHES.items()}
+
+ results = [
+ {
+ "team_id": team.id,
+ "evaluation": _entry_status(batches[EVALUATION][team.id]),
+ "definitions": _entry_status(batches[DEFINITIONS][team.id]),
+ "definitions_no_cohorts": _entry_status(batches[DEFINITIONS_NO_COHORTS][team.id]),
+ }
+ for team in teams
+ ]
+
+ return response.Response({"results": results})
+
+ @validated_request(
+ request_serializer=StaffCacheMutationSerializer,
+ responses={202: OpenApiResponse(response=StaffCacheMutationResponseSerializer)},
+ )
+ @action(methods=["POST"], detail=False)
+ def rebuild(self, request: request.Request, **kwargs) -> response.Response:
+ # Evaluation cache goes through enqueue_evaluation_cache_invalidation, raising the same
+ # invalidation signal (Kafka dual-write + Celery) an organic flag create/update/delete
+ # raises, rather than a staff-only side channel.
+ return _dispatch_mutation(
+ request,
+ request.validated_data["team_ids"],
+ request.validated_data["caches"],
+ evaluation_fn=enqueue_evaluation_cache_invalidation,
+ definitions_fn=update_team_flags_cache.delay,
+ log_event="flags_staff_cache_rebuild",
+ )
+
+ @validated_request(
+ query_serializer=StaffCacheEntryQuerySerializer,
+ responses={200: OpenApiResponse(response=StaffCacheEntryResponseSerializer)},
+ )
+ @action(methods=["GET"], detail=False)
+ def entry(self, request: request.Request, **kwargs) -> response.Response:
+ team_id: int = request.validated_query_data["team_id"]
+ cache_kind: str = request.validated_query_data["cache"]
+
+ team = Team.objects.filter(id=team_id).first()
+ if team is None:
+ raise NotFound(f"Team {team_id} not found.")
+
+ hypercache = _READABLE_HYPERCACHES[cache_kind]
+ cache_entry = hypercache.batch_get_from_cache([team])[team.id]
+ data, _, _etag = cache_entry
+ # _entry_status reports a redis hit whose stored payload is empty as a miss, same as a
+ # genuine cache miss, so entry() agrees with what list() shows for the same team/cache.
+ source = _entry_status(cache_entry)["source"]
+
+ logger.info(
+ "flags_staff_cache_entry_viewed",
+ staff_user_id=request.user.id,
+ was_impersonated=is_impersonated(request),
+ team_id=team_id,
+ cache=cache_kind,
+ )
+
+ return response.Response({"team_id": team_id, "cache": cache_kind, "source": source, "data": data})
+
+ @validated_request(
+ request_serializer=StaffCacheMutationSerializer,
+ responses={202: OpenApiResponse(response=StaffCacheMutationResponseSerializer)},
+ )
+ @action(methods=["POST"], detail=False)
+ def clear(self, request: request.Request, **kwargs) -> response.Response:
+ # No shared invalidation signal to raise here, unlike rebuild: the Kafka message is
+ # defined as an "invalidate/rebuild" trigger with no delete semantic, so this goes
+ # straight to the cache-clearing tasks instead of enqueue_evaluation_cache_invalidation.
+ return _dispatch_mutation(
+ request,
+ request.validated_data["team_ids"],
+ request.validated_data["caches"],
+ evaluation_fn=clear_team_evaluation_cache.delay,
+ definitions_fn=clear_team_definitions_cache.delay,
+ log_event="flags_staff_cache_clear",
+ )
diff --git a/products/feature_flags/backend/api/staff_teams.py b/products/feature_flags/backend/api/staff_teams.py
new file mode 100644
index 000000000000..260ebfa9557a
--- /dev/null
+++ b/products/feature_flags/backend/api/staff_teams.py
@@ -0,0 +1,107 @@
+from django.db.models import F, Q
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema_serializer
+from rest_framework import request, response, serializers, viewsets
+from rest_framework.permissions import IsAuthenticated
+
+from posthog.api.mixins import validated_request
+from posthog.models.team import Team
+from posthog.permissions import IsStaffUser
+
+DEFAULT_LIMIT = 25
+MAX_LIMIT = 100
+MIN_SEARCH_LENGTH = 2
+
+
+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."
+ ),
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ default=DEFAULT_LIMIT,
+ min_value=1,
+ max_value=MAX_LIMIT,
+ help_text=f"Maximum number of teams to return (default {DEFAULT_LIMIT}, max {MAX_LIMIT}).",
+ )
+
+ def validate_search(self, value: str) -> str:
+ stripped = value.strip()
+ # Digit-only queries are exact team-id lookups (Q(id=...) below) and are allowed at a
+ # single digit so deep links to low-id teams resolve; everything else needs >= 2 chars.
+ # isdecimal() (not isdigit()) since isdigit() also accepts non-ASCII digit-like characters
+ # (e.g. superscript "²") that int() can't parse, which would 500 below.
+ min_length = 1 if stripped.isdecimal() else MIN_SEARCH_LENGTH
+ if len(stripped) < min_length:
+ raise serializers.ValidationError(
+ f"Search must be at least {MIN_SEARCH_LENGTH} characters, or a numeric team id."
+ )
+ return stripped
+
+
+class StaffTeamResultSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="Team id.")
+ name = serializers.CharField(help_text="Team name.")
+ api_token = serializers.CharField(help_text="Team api_token (used as the flags evaluation cache key).")
+ organization_id = serializers.CharField(help_text="Organization uuid that owns the team.")
+ organization_name = serializers.CharField(help_text="Organization name that owns the team.")
+ project_id = serializers.IntegerField(help_text="Project id the team belongs to.")
+
+
+@extend_schema_serializer(many=False)
+class StaffTeamSearchResponseSerializer(serializers.Serializer):
+ results = StaffTeamResultSerializer(many=True, help_text="Matching teams.")
+
+
+class FeatureFlagsStaffTeamSearchViewSet(viewsets.ViewSet):
+ """
+ Staff-only, unscoped team search across every organization.
+
+ Unlike TeamViewSet (membership-scoped via TeamAndOrgViewSetMixin), staff need to look up
+ teams they do not belong to in order to inspect and rebuild flag caches. Registered on the
+ root router so it is not team-nested. Exposes the same fields Django admin's TeamAdmin
+ already shows staff un-redacted, so no new data exposure.
+ """
+
+ # 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=StaffTeamSearchQuerySerializer,
+ responses={200: OpenApiResponse(response=StaffTeamSearchResponseSerializer)},
+ )
+ def list(self, request: request.Request, **kwargs) -> response.Response:
+ search: str = request.validated_query_data["search"]
+ limit: int = request.validated_query_data["limit"]
+
+ if search.isdecimal() and len(search) < MIN_SEARCH_LENGTH:
+ # A single-digit search is only allowed as an exact team-id lookup (see
+ # validate_search above); matching it against name/organization name too would
+ # turn a 1-character query into a broad substring scan, defeating that guard.
+ query = Q(id=int(search))
+ else:
+ query = Q(name__icontains=search) | Q(api_token=search) | Q(organization__name__icontains=search)
+ if search.isdecimal():
+ query |= Q(id=int(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 if
+ # this shows up in slow-query logs.
+ # .values() keys are aliased to match the serializer fields, so the rows serialize
+ # directly (the response serializer stringifies the organization UUID).
+ teams = (
+ Team.objects.filter(query)
+ .annotate(organization_name=F("organization__name"))
+ .order_by("id")
+ .values("id", "name", "api_token", "organization_id", "organization_name", "project_id")[:limit]
+ )
+
+ return response.Response(StaffTeamSearchResponseSerializer({"results": list(teams)}).data)
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index b1fb07db0b15..99a2ff00fef5 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -1020,10 +1020,12 @@ def _produce_invalidation(team_id: int) -> None:
def _enqueue_invalidation(team_id: int) -> None:
"""Run from `transaction.on_commit`: route to Kafka if enabled, otherwise Celery.
- Deferring until commit avoids race conditions where the Celery worker reads
- pre-commit state. Shared by all four signal handlers wired to the
- flag-invalidation topic. Cohort invalidation is intentionally not routed
- here — cohort changes flow through their own topic.
+ Model signal handlers wrap this in `transaction.on_commit`: deferring until commit
+ avoids race conditions where the Celery worker reads pre-commit state. Callers with no
+ open transaction to defer past (e.g. staff tooling, via `enqueue_evaluation_cache_invalidation`)
+ call it directly. Shared by all four signal handlers wired to the flag-invalidation topic.
+ Cohort invalidation is intentionally not routed here, since cohort changes flow through their
+ own topic.
The two paths are mutually exclusive so the rollout proves the Kafka path
actually works end to end: Celery is not a fallback when the flag is on,
@@ -1034,7 +1036,13 @@ def _enqueue_invalidation(team_id: int) -> None:
is dropped, not retried via Celery. Watch `flags_cache_invalidation_produce_failed`
logs during rollout. Celery's `.delay()` is allowed to raise when the flag
is off — it's the sole path in that case and operators want broker failures loud.
+
+ Guarded on FLAGS_REDIS_URL here (not just at each call site) so every caller, including
+ ones outside a signal handler, gets the same no-op-when-unconfigured behavior for free.
"""
+ if not settings.FLAGS_REDIS_URL:
+ return
+
from products.feature_flags.backend.tasks import update_team_service_flags_cache
if _route_to_kafka(team_id):
@@ -1043,6 +1051,13 @@ def _enqueue_invalidation(team_id: int) -> None:
update_team_service_flags_cache.delay(team_id)
+def enqueue_evaluation_cache_invalidation(team_id: int) -> None:
+ """Public entry point for `_enqueue_invalidation`, for callers outside a model signal handler
+ (e.g. staff tooling) that want a rebuild to raise the exact same invalidation signal (Kafka
+ or Celery routing) that an organic flag create/update/delete raises."""
+ _enqueue_invalidation(team_id)
+
+
@receiver(post_save, sender=FeatureFlag)
@receiver(post_delete, sender=FeatureFlag)
def feature_flag_changed_flags_cache(sender, instance: "FeatureFlag", **kwargs):
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index 8ffa67eeac51..043416b3f715 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -551,7 +551,7 @@ def update_flag_caches(team: Team):
emit_cache_sync_metrics(result, "feature_flags", "flags_without_cohorts.json", size=size_without_cohorts)
-def clear_flag_definition_caches(team: Team, kinds: list[str] | None = None):
+def clear_flag_definition_caches(team: Team | int, kinds: list[str] | None = None):
"""
Clear the flag definitions cache for a team.
diff --git a/products/feature_flags/backend/routes.py b/products/feature_flags/backend/routes.py
index cc2f95dfd382..239676ab4406 100644
--- a/products/feature_flags/backend/routes.py
+++ b/products/feature_flags/backend/routes.py
@@ -1,11 +1,30 @@
from posthog.api.routing import RouterRegistry
-from products.feature_flags.backend.api import feature_flag, flag_value, organization_feature_flag, scheduled_change
+from products.feature_flags.backend.api import (
+ feature_flag,
+ flag_value,
+ organization_feature_flag,
+ scheduled_change,
+ staff_cache,
+ staff_teams,
+)
def register_routes(routers: RouterRegistry) -> None:
# Library-side feature flag evaluation (legacy root path).
routers.root.register(r"feature_flag", feature_flag.LegacyFeatureFlagViewSet)
+
+ # Staff-only, unscoped flags tooling: root-level so it is not team-nested.
+ routers.root.register(
+ r"feature_flags_staff_teams",
+ staff_teams.FeatureFlagsStaffTeamSearchViewSet,
+ "feature_flags_staff_teams",
+ )
+ routers.root.register(
+ r"feature_flags_staff_cache",
+ staff_cache.FeatureFlagsStaffCacheViewSet,
+ "feature_flags_staff_cache",
+ )
routers.projects.register(
r"feature_flags", feature_flag.FeatureFlagViewSet, "project_feature_flags", ["project_id"]
)
diff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.py
index 515c59a44650..8a294c87464e 100644
--- a/products/feature_flags/backend/tasks.py
+++ b/products/feature_flags/backend/tasks.py
@@ -17,6 +17,7 @@ from posthog.tasks.utils import CeleryQueue, PushGatewayTask
from products.feature_flags.backend.canary import run_local_eval_canary
from products.feature_flags.backend.flags_cache import (
cleanup_stale_expiry_tracking,
+ clear_flags_cache,
get_cache_stats,
refresh_expiring_flags_caches,
update_flags_cache,
@@ -24,6 +25,7 @@ from products.feature_flags.backend.flags_cache import (
from products.feature_flags.backend.local_evaluation import (
FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,
+ clear_flag_definition_caches,
update_flag_caches,
)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -87,6 +89,20 @@ def update_team_service_flags_cache(team_id: int) -> None:
).inc()
+@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS.value)
+@skip_team_scope_audit
+def clear_team_evaluation_cache(team_id: int) -> None:
+ """Clear the /flags evaluation cache for a specific team, enqueued by staff tooling."""
+ clear_flags_cache(team_id)
+
+
+@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS.value)
+@skip_team_scope_audit
+def clear_team_definitions_cache(team_id: int) -> None:
+ """Clear the /flags/definitions local-eval cache for a specific team, enqueued by staff tooling."""
+ clear_flag_definition_caches(team_id)
+
+
@shared_task(bind=True, base=PushGatewayTask, ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value)
def refresh_expiring_flags_cache_entries(self: PushGatewayTask) -> None:
"""
diff --git a/products/feature_flags/backend/test/test_staff_cache_api.py b/products/feature_flags/backend/test/test_staff_cache_api.py
new file mode 100644
index 000000000000..05b4e86b50dd
--- /dev/null
+++ b/products/feature_flags/backend/test/test_staff_cache_api.py
@@ -0,0 +1,199 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+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.flags_cache import flags_hypercache
+from products.feature_flags.backend.local_evaluation import (
+ flag_definitions_hypercache,
+ flag_definitions_without_cohorts_hypercache,
+)
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+REBUILD_URL = "/api/feature_flags_staff_cache/rebuild/"
+CLEAR_URL = "/api/feature_flags_staff_cache/clear/"
+ENTRY_URL = "/api/feature_flags_staff_cache/entry/"
+
+
+def _called_once_with(mock, team_id):
+ mock.assert_called_once_with(team_id)
+
+
+def _delay_called_once_with(mock, team_id):
+ mock.delay.assert_called_once_with(team_id)
+
+
+# (label, url, evaluation patch target, definitions task name, evaluation-call assertion) - rebuild
+# and clear share the same enqueue/found-not-found shape. Rebuild's evaluation cache goes through
+# `enqueue_evaluation_cache_invalidation` directly (the same signal an organic flag change raises),
+# while everything else still goes through a plain Celery `.delay()`.
+MUTATION_CASES = [
+ ("rebuild", REBUILD_URL, "enqueue_evaluation_cache_invalidation", "update_team_flags_cache", _called_once_with),
+ ("clear", CLEAR_URL, "clear_team_evaluation_cache", "clear_team_definitions_cache", _delay_called_once_with),
+]
+
+
+class TestFeatureFlagsStaffCacheAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+
+ def test_non_staff_user_gets_403_on_all_actions(self):
+ self.user.is_staff = False
+ self.user.save()
+
+ status_response = self.client.get(f"/api/feature_flags_staff_cache/?team_ids={self.team.id}")
+ self.assertEqual(status_response.status_code, status.HTTP_403_FORBIDDEN)
+
+ rebuild_response = self.client.post(REBUILD_URL, {"team_ids": [self.team.id]}, format="json")
+ self.assertEqual(rebuild_response.status_code, status.HTTP_403_FORBIDDEN)
+
+ clear_response = self.client.post(CLEAR_URL, {"team_ids": [self.team.id]}, format="json")
+ self.assertEqual(clear_response.status_code, status.HTTP_403_FORBIDDEN)
+
+ entry_response = self.client.get(ENTRY_URL, {"team_id": str(self.team.id), "cache": "evaluation"})
+ self.assertEqual(entry_response.status_code, status.HTTP_403_FORBIDDEN)
+
+ @parameterized.expand(MUTATION_CASES)
+ def test_mutation_enqueues_both_tasks_and_returns_202(
+ self, _name, url, evaluation_target, definitions_task, assert_evaluation_called
+ ):
+ with (
+ patch(f"products.feature_flags.backend.api.staff_cache.{evaluation_target}") as mock_evaluation,
+ patch(f"products.feature_flags.backend.api.staff_cache.{definitions_task}") as mock_definitions,
+ ):
+ response = self.client.post(url, {"team_ids": [self.team.id]}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
+
+ self.assertEqual(response.json()["queued_team_ids"], [self.team.id])
+ self.assertEqual(response.json()["not_found_team_ids"], [])
+ assert_evaluation_called(mock_evaluation, self.team.id)
+ mock_definitions.delay.assert_called_once_with(self.team.id)
+
+ @parameterized.expand(MUTATION_CASES)
+ def test_mutation_respects_caches_filter(
+ self, _name, url, evaluation_target, definitions_task, assert_evaluation_called
+ ):
+ with (
+ patch(f"products.feature_flags.backend.api.staff_cache.{evaluation_target}") as mock_evaluation,
+ patch(f"products.feature_flags.backend.api.staff_cache.{definitions_task}") as mock_definitions,
+ ):
+ response = self.client.post(url, {"team_ids": [self.team.id], "caches": ["evaluation"]}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
+
+ assert_evaluation_called(mock_evaluation, self.team.id)
+ mock_definitions.delay.assert_not_called()
+
+ @parameterized.expand(MUTATION_CASES)
+ def test_mutation_reports_unknown_team_ids(
+ self, _name, url, evaluation_target, definitions_task, assert_evaluation_called
+ ):
+ missing_id = self.team.id + 9999
+ with (
+ patch(f"products.feature_flags.backend.api.staff_cache.{evaluation_target}") as mock_evaluation,
+ patch(f"products.feature_flags.backend.api.staff_cache.{definitions_task}"),
+ ):
+ response = self.client.post(url, {"team_ids": [self.team.id, missing_id]}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
+
+ self.assertEqual(response.json()["queued_team_ids"], [self.team.id])
+ self.assertEqual(response.json()["not_found_team_ids"], [missing_id])
+ assert_evaluation_called(mock_evaluation, self.team.id)
+
+ def test_rebuild_over_max_team_ids_returns_400(self):
+ team_ids = list(range(1, MAX_TEAMS_PER_MUTATION + 2))
+ response = self.client.post(REBUILD_URL, {"team_ids": team_ids}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_status_reflects_real_cache_state(self):
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="status-flag",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+
+ flags_hypercache.update_cache(self.team)
+ warm = self.client.get(f"/api/feature_flags_staff_cache/?team_ids={self.team.id}")
+ self.assertEqual(warm.status_code, status.HTTP_200_OK)
+ evaluation = warm.json()["results"][0]["evaluation"]
+ self.assertEqual(evaluation["source"], "redis")
+ self.assertEqual(evaluation["flag_count"], 1)
+
+ flags_hypercache.clear_cache(self.team)
+ cold = self.client.get(f"/api/feature_flags_staff_cache/?team_ids={self.team.id}")
+ self.assertEqual(cold.json()["results"][0]["evaluation"]["source"], "miss")
+
+ def test_status_dedupes_repeated_team_ids(self):
+ # A caller passing the same team id twice (e.g. ?team_ids=1&team_ids=1) should get one
+ # row back, not a duplicate per repetition.
+ response = self.client.get(f"/api/feature_flags_staff_cache/?team_ids={self.team.id}&team_ids={self.team.id}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.json()["results"]), 1)
+
+ def test_status_reports_the_two_definitions_variants_independently(self):
+ self.addCleanup(flag_definitions_hypercache.clear_cache, self.team)
+ self.addCleanup(flag_definitions_without_cohorts_hypercache.clear_cache, self.team)
+
+ # Only warm the without-cohorts variant; the with-cohorts variant stays cold.
+ flag_definitions_without_cohorts_hypercache.update_cache(self.team)
+
+ response = self.client.get(f"/api/feature_flags_staff_cache/?team_ids={self.team.id}")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"][0]
+ self.assertEqual(results["definitions_no_cohorts"]["source"], "redis")
+ self.assertEqual(results["definitions"]["source"], "miss")
+
+ @parameterized.expand(
+ [
+ ("evaluation", flags_hypercache),
+ ("definitions", flag_definitions_hypercache),
+ ("definitions_no_cohorts", flag_definitions_without_cohorts_hypercache),
+ ]
+ )
+ def test_entry_reads_the_hypercache_matching_the_cache_param(self, cache_kind, hypercache):
+ # self.team is shared across every test in this class (setUpTestData), and Redis writes
+ # aren't rolled back between tests like the DB is, so clean up this team's Redis entries
+ # regardless of how the test ends.
+ self.addCleanup(flags_hypercache.clear_cache, self.team)
+ self.addCleanup(flag_definitions_hypercache.clear_cache, self.team)
+ self.addCleanup(flag_definitions_without_cohorts_hypercache.clear_cache, self.team)
+
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="entry-flag",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ hypercache.update_cache(self.team)
+
+ warm = self.client.get(ENTRY_URL, {"team_id": str(self.team.id), "cache": cache_kind})
+ self.assertEqual(warm.status_code, status.HTTP_200_OK)
+ self.assertEqual(warm.json()["source"], "redis")
+ self.assertEqual(len(warm.json()["data"]["flags"]), 1)
+
+ # Any kind other than the one just warmed should still be cold.
+ other_kind = next(kind for kind in READABLE_CACHE_CHOICES if kind != cache_kind)
+ cold = self.client.get(ENTRY_URL, {"team_id": str(self.team.id), "cache": other_kind})
+ self.assertEqual(cold.json()["source"], "miss")
+ self.assertIsNone(cold.json()["data"])
+
+ def test_entry_reports_miss_for_a_warm_empty_sentinel(self):
+ # A prior write that cached "nothing to see here" (e.g. a team with zero flags) stores
+ # the empty sentinel in redis rather than an actual miss. entry() should report that the
+ # same way list()'s _entry_status does: as a miss, not as a redis hit with null data.
+ self.addCleanup(flags_hypercache.clear_cache, self.team)
+ flags_hypercache.set_cache_value(self.team, None)
+
+ response = self.client.get(ENTRY_URL, {"team_id": str(self.team.id), "cache": "evaluation"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["source"], "miss")
+ self.assertIsNone(response.json()["data"])
+
+ def test_entry_returns_404_for_unknown_team(self):
+ 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)
diff --git a/products/feature_flags/backend/test/test_staff_teams_api.py b/products/feature_flags/backend/test/test_staff_teams_api.py
new file mode 100644
index 000000000000..c8490db6eda3
--- /dev/null
+++ b/products/feature_flags/backend/test/test_staff_teams_api.py
@@ -0,0 +1,106 @@
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models import Organization, Team
+
+
+class TestFeatureFlagsStaffTeamSearchAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+
+ def test_non_staff_user_gets_403(self):
+ self.user.is_staff = False
+ self.user.save()
+
+ response = self.client.get("/api/feature_flags_staff_teams/?search=Test")
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_staff_can_find_team_in_organization_they_do_not_belong_to(self):
+ # The whole point of this endpoint: staff must reach teams they aren't a member of.
+ # This guards against someone reintroducing membership scoping (an org filter or
+ # TeamAndOrgViewSetMixin) on the viewset.
+ other_org = Organization.objects.create(name="Unrelated Org")
+ other_team = Team.objects.create(organization=other_org, name="Cross Org Team")
+ self.assertFalse(self.user.organization_memberships.filter(organization=other_org).exists())
+
+ response = self.client.get("/api/feature_flags_staff_teams/?search=Cross Org Team")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ returned_ids = [team["id"] for team in response.json()["results"]]
+ self.assertIn(other_team.id, returned_ids)
+
+ @parameterized.expand(
+ [
+ ("exact_id", lambda self: str(self.searchable_team.id)),
+ ("padded_exact_id", lambda self: f" {self.searchable_team.id} "),
+ ("partial_name", lambda self: "Searchable"),
+ ("exact_api_token", lambda self: self.searchable_team.api_token),
+ ("partial_org_name", lambda self: "Findable"),
+ ]
+ )
+ def test_search_matches_by_field(self, _name, search_value_fn):
+ org = Organization.objects.create(name="Findable Organization")
+ self.searchable_team = Team.objects.create(organization=org, name="Searchable Team")
+
+ response = self.client.get("/api/feature_flags_staff_teams/", {"search": search_value_fn(self)})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ returned_ids = [team["id"] for team in response.json()["results"]]
+ self.assertIn(self.searchable_team.id, returned_ids)
+
+ def test_result_shape(self):
+ org = Organization.objects.create(name="Shape Org")
+ team = Team.objects.create(organization=org, name="Shape Team")
+
+ response = self.client.get("/api/feature_flags_staff_teams/", {"search": "Shape Team"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ result = next(r for r in response.json()["results"] if r["id"] == team.id)
+ self.assertEqual(result["name"], "Shape Team")
+ self.assertEqual(result["api_token"], team.api_token)
+ self.assertEqual(result["organization_id"], str(org.id))
+ self.assertEqual(result["organization_name"], "Shape Org")
+ self.assertEqual(result["project_id"], team.project_id)
+
+ @parameterized.expand([("single_letter", "a"), ("empty", "")])
+ def test_non_numeric_search_below_min_length_returns_400(self, _name, search):
+ # A single-digit numeric id lookup is allowed (see exact_id case above); a single
+ # letter or empty string is not, so an over-broad query never returns half the table.
+ response = self.client.get("/api/feature_flags_staff_teams/", {"search": search})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_single_digit_search_only_matches_by_id_not_by_name_or_org_substring(self):
+ # A single-digit search is allowed below MIN_SEARCH_LENGTH only as an exact team-id
+ # lookup (see exact_id case above). If it also matched name/organization name via
+ # icontains, a 1-character query could still return a broad, unbounded set of teams,
+ # defeating the min-length guard.
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org, name="Team")
+ digit = next(d for d in "0123456789" if d not in str(team.id))
+ team.name = f"Team{digit}"
+ org.name = f"Org{digit}"
+ team.save(update_fields=["name"])
+ org.save(update_fields=["name"])
+
+ response = self.client.get("/api/feature_flags_staff_teams/", {"search": digit})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ returned_ids = [result["id"] for result in response.json()["results"]]
+ self.assertNotIn(team.id, returned_ids)
+
+ def test_limit_is_capped(self):
+ response = self.client.get("/api/feature_flags_staff_teams/", {"search": "Test", "limit": "1000"})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_limit_bounds_number_of_results(self):
+ org = Organization.objects.create(name="Bulk Org")
+ for i in range(3):
+ Team.objects.create(organization=org, name=f"Bulk Team {i}")
+
+ response = self.client.get("/api/feature_flags_staff_teams/", {"search": "Bulk Team", "limit": "2"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.json()["results"]), 2)
diff --git a/products/feature_flags/backend/test/test_tasks.py b/products/feature_flags/backend/test/test_tasks.py
new file mode 100644
index 000000000000..a5f6e088ebb0
--- /dev/null
+++ b/products/feature_flags/backend/test/test_tasks.py
@@ -0,0 +1,19 @@
+from posthog.test.base import BaseTest
+
+from products.feature_flags.backend.local_evaluation import flag_definitions_hypercache, update_flag_caches
+from products.feature_flags.backend.tasks import clear_team_definitions_cache
+
+
+class TestClearTeamDefinitionsCache(BaseTest):
+ def test_clears_cache_for_existing_team(self):
+ update_flag_caches(self.team)
+ _, source = flag_definitions_hypercache.get_from_cache_with_source(self.team)
+ assert source == "redis"
+
+ clear_team_definitions_cache(self.team.id)
+
+ _, source = flag_definitions_hypercache.get_from_cache_with_source(self.team)
+ assert source == "db"
+
+ def test_missing_team_does_not_raise(self):
+ clear_team_definitions_cache(999999999)
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index a672c2596119..5b581e306c17 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -7,6 +7,134 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * * `redis` - redis
+ * * `miss` - miss
+ */
+export type StaffCacheSourceEnumApi = (typeof StaffCacheSourceEnumApi)[keyof typeof StaffCacheSourceEnumApi]
+
+export const StaffCacheSourceEnumApi = {
+ Redis: 'redis',
+ Miss: 'miss',
+} as const
+
+export interface StaffCacheEntryStatusApi {
+ /** 'redis' when a warm entry is cached, or 'miss' when nothing is cached in Redis.
+ *
+ * * `redis` - redis
+ * * `miss` - miss */
+ source: StaffCacheSourceEnumApi
+ /**
+ * Number of flags in the cached payload, or null on a miss.
+ * @nullable
+ */
+ flag_count: number | null
+}
+
+export interface StaffCacheTeamStatusApi {
+ /** Team id. */
+ team_id: number
+ /** Status of the /flags evaluation cache. */
+ evaluation: StaffCacheEntryStatusApi
+ /** Status of the /flags/definitions local-eval cache (with-cohorts variant). */
+ definitions: StaffCacheEntryStatusApi
+ /** Status of the /flags/definitions local-eval cache (without-cohorts variant, cohort filters transformed to properties for simple SDK clients). */
+ definitions_no_cohorts: StaffCacheEntryStatusApi
+}
+
+export interface StaffCacheStatusResponseApi {
+ /** Per-team cache status. */
+ results: StaffCacheTeamStatusApi[]
+}
+
+/**
+ * * `evaluation` - evaluation
+ * * `definitions` - definitions
+ */
+export type CachesEnumApi = (typeof CachesEnumApi)[keyof typeof CachesEnumApi]
+
+export const CachesEnumApi = {
+ Evaluation: 'evaluation',
+ Definitions: 'definitions',
+} as const
+
+export interface StaffCacheMutationApi {
+ /**
+ * Team ids to act on (max 50 per request).
+ * @maxItems 50
+ */
+ team_ids: number[]
+ /** Which logical caches to act on: 'evaluation' (the /flags cache) and/or 'definitions' (the /flags/definitions local-eval cache). Defaults to both. */
+ caches?: CachesEnumApi[]
+}
+
+export interface StaffCacheMutationResponseApi {
+ /** Team ids for which the requested action's tasks were enqueued. */
+ queued_team_ids: number[]
+ /** Requested team ids that do not exist. */
+ not_found_team_ids: number[]
+}
+
+/**
+ * Raw cached payload as stored in Redis, or null on a miss.
+ * @nullable
+ */
+export type StaffCacheEntryResponseApiData = { [key: string]: unknown } | null
+
+/**
+ * * `evaluation` - evaluation
+ * * `definitions` - definitions
+ * * `definitions_no_cohorts` - definitions_no_cohorts
+ */
+export type CacheEnumApi = (typeof CacheEnumApi)[keyof typeof CacheEnumApi]
+
+export const CacheEnumApi = {
+ Evaluation: 'evaluation',
+ Definitions: 'definitions',
+ DefinitionsNoCohorts: 'definitions_no_cohorts',
+} as const
+
+export interface StaffCacheEntryResponseApi {
+ /** Team id. */
+ team_id: number
+ /** Which cache this entry is for.
+ *
+ * * `evaluation` - evaluation
+ * * `definitions` - definitions
+ * * `definitions_no_cohorts` - definitions_no_cohorts */
+ cache: CacheEnumApi
+ /** 'redis' when a warm entry is cached, or 'miss' when nothing is cached in Redis.
+ *
+ * * `redis` - redis
+ * * `miss` - miss */
+ source: StaffCacheSourceEnumApi
+ /**
+ * Raw cached payload as stored in Redis, or null on a miss.
+ * @nullable
+ */
+ data: StaffCacheEntryResponseApiData
+}
+
+export interface StaffTeamResultApi {
+ /** Team id. */
+ id: number
+ /** Team name. */
+ name: string
+ /** Team api_token (used as the flags evaluation cache key). */
+ api_token: string
+ /** Organization uuid that owns the team. */
+ organization_id: string
+ /** Organization name that owns the team. */
+ organization_name: string
+ /** Project id the team belongs to. */
+ project_id: number
+}
+
+export interface StaffTeamSearchResponseApi {
+ /** Matching teams. */
+ results: StaffTeamResultApi[]
+}
+
export interface CopyFlagsRequestApi {
/** Key of the feature flag to copy */
feature_flag_key: string
@@ -1434,6 +1562,53 @@ export interface PatchedScheduledChangeApi {
readonly timezone?: string | null
}
+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.
+ * @maxItems 50
+ */
+ team_ids: number[]
+}
+
+export type FeatureFlagsStaffCacheEntryRetrieveParams = {
+ /**
+ * Which cache to fetch: 'evaluation' (the /flags cache), 'definitions' (the /flags/definitions local-eval cache, with-cohorts variant), or 'definitions_no_cohorts' (the without-cohorts variant served to simple SDK clients).
+ *
+ * * `evaluation` - evaluation
+ * * `definitions` - definitions
+ * * `definitions_no_cohorts` - definitions_no_cohorts
+ * @minLength 1
+ */
+ cache: FeatureFlagsStaffCacheEntryRetrieveCache
+ /**
+ * Team id to fetch the cache entry for.
+ */
+ team_id: number
+}
+
+export type FeatureFlagsStaffCacheEntryRetrieveCache =
+ (typeof FeatureFlagsStaffCacheEntryRetrieveCache)[keyof typeof FeatureFlagsStaffCacheEntryRetrieveCache]
+
+export const FeatureFlagsStaffCacheEntryRetrieveCache = {
+ Evaluation: 'evaluation',
+ Definitions: 'definitions',
+ DefinitionsNoCohorts: 'definitions_no_cohorts',
+} as const
+
+export type FeatureFlagsStaffTeamsListParams = {
+ /**
+ * Maximum number of teams to return (default 25, max 100).
+ * @minimum 1
+ * @maximum 100
+ */
+ 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.
+ * @minLength 1
+ */
+ search: string
+}
+
export type OrgFeatureFlagsKeysParams = {
/**
* Page size (max 100)
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index fb37bb63f3fc..ed58be16ec44 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -33,6 +33,9 @@ import type {
FeatureFlagsEvaluationReasonsRetrieveParams,
FeatureFlagsListParams,
FeatureFlagsMyFlagsRetrieveParams,
+ FeatureFlagsStaffCacheEntryRetrieveParams,
+ FeatureFlagsStaffCacheListParams,
+ FeatureFlagsStaffTeamsListParams,
FlagValueResponseApi,
FlagValueValuesRetrieveParams,
MyFlagsResponseApi,
@@ -45,6 +48,11 @@ import type {
PatchedScheduledChangeApi,
ScheduledChangeApi,
ScheduledChangesListParams,
+ StaffCacheEntryResponseApi,
+ StaffCacheMutationApi,
+ StaffCacheMutationResponseApi,
+ StaffCacheStatusResponseApi,
+ StaffTeamSearchResponseApi,
UserBlastRadiusRequestApi,
UserBlastRadiusResponseApi,
} from './api.schemas'
@@ -66,6 +74,172 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getFeatureFlagsStaffCacheListUrl = (params: FeatureFlagsStaffCacheListParams) => {
+ 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_cache/?${stringifiedParams}`
+ : `/api/feature_flags_staff_cache/`
+}
+
+/**
+ * Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
+ *
+ * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
+ * or clears both definitions-cache variants together). Status/entry can read a third, narrower
+ * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
+ * individually readable even though they're only mutated as a pair.
+ *
+ * Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
+ * when a flag changes) rather than re-implementing cache-write logic. Registered on the root
+ * router so it is not team-nested; staff act on teams they do not belong to.
+ */
+export const featureFlagsStaffCacheList = async (
+ params: FeatureFlagsStaffCacheListParams,
+ options?: RequestInit
+): Promise<StaffCacheStatusResponseApi> => {
+ return apiMutator<StaffCacheStatusResponseApi>(getFeatureFlagsStaffCacheListUrl(params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getFeatureFlagsStaffCacheClearCreateUrl = () => {
+ return `/api/feature_flags_staff_cache/clear/`
+}
+
+/**
+ * Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
+ *
+ * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
+ * or clears both definitions-cache variants together). Status/entry can read a third, narrower
+ * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
+ * individually readable even though they're only mutated as a pair.
+ *
+ * Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
+ * when a flag changes) rather than re-implementing cache-write logic. Registered on the root
+ * router so it is not team-nested; staff act on teams they do not belong to.
+ */
+export const featureFlagsStaffCacheClearCreate = async (
+ staffCacheMutationApi: StaffCacheMutationApi,
+ options?: RequestInit
+): Promise<StaffCacheMutationResponseApi> => {
+ return apiMutator<StaffCacheMutationResponseApi>(getFeatureFlagsStaffCacheClearCreateUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(staffCacheMutationApi),
+ })
+}
+
+export const getFeatureFlagsStaffCacheEntryRetrieveUrl = (params: FeatureFlagsStaffCacheEntryRetrieveParams) => {
+ 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_cache/entry/?${stringifiedParams}`
+ : `/api/feature_flags_staff_cache/entry/`
+}
+
+/**
+ * Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
+ *
+ * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
+ * or clears both definitions-cache variants together). Status/entry can read a third, narrower
+ * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
+ * individually readable even though they're only mutated as a pair.
+ *
+ * Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
+ * when a flag changes) rather than re-implementing cache-write logic. Registered on the root
+ * router so it is not team-nested; staff act on teams they do not belong to.
+ */
+export const featureFlagsStaffCacheEntryRetrieve = async (
+ params: FeatureFlagsStaffCacheEntryRetrieveParams,
+ options?: RequestInit
+): Promise<StaffCacheEntryResponseApi> => {
+ return apiMutator<StaffCacheEntryResponseApi>(getFeatureFlagsStaffCacheEntryRetrieveUrl(params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getFeatureFlagsStaffCacheRebuildCreateUrl = () => {
+ return `/api/feature_flags_staff_cache/rebuild/`
+}
+
+/**
+ * Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
+ *
+ * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
+ * or clears both definitions-cache variants together). Status/entry can read a third, narrower
+ * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
+ * individually readable even though they're only mutated as a pair.
+ *
+ * Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
+ * when a flag changes) rather than re-implementing cache-write logic. Registered on the root
+ * router so it is not team-nested; staff act on teams they do not belong to.
+ */
+export const featureFlagsStaffCacheRebuildCreate = async (
+ staffCacheMutationApi: StaffCacheMutationApi,
+ options?: RequestInit
+): Promise<StaffCacheMutationResponseApi> => {
+ return apiMutator<StaffCacheMutationResponseApi>(getFeatureFlagsStaffCacheRebuildCreateUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(staffCacheMutationApi),
+ })
+}
+
+export const getFeatureFlagsStaffTeamsListUrl = (params: FeatureFlagsStaffTeamsListParams) => {
+ 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_teams/?${stringifiedParams}`
+ : `/api/feature_flags_staff_teams/`
+}
+
+/**
+ * Staff-only, unscoped team search across every organization.
+ *
+ * Unlike TeamViewSet (membership-scoped via TeamAndOrgViewSetMixin), staff need to look up
+ * teams they do not belong to in order to inspect and rebuild flag caches. Registered on the
+ * root router so it is not team-nested. Exposes the same fields Django admin's TeamAdmin
+ * already shows staff un-redacted, so no new data exposure.
+ */
+export const featureFlagsStaffTeamsList = async (
+ params: FeatureFlagsStaffTeamsListParams,
+ options?: RequestInit
+): Promise<StaffTeamSearchResponseApi> => {
+ return apiMutator<StaffTeamSearchResponseApi>(getFeatureFlagsStaffTeamsListUrl(params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getOrgFeatureFlagsRetrieveUrl = (organizationId: string, featureFlagKey: string) => {
return `/api/organizations/${organizationId}/feature_flags/${featureFlagKey}/`
}
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index 99756c95ffe4..515b98cde919 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -9,6 +9,68 @@
*/
import * as zod from 'zod'
+/**
+ * Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
+ *
+ * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
+ * or clears both definitions-cache variants together). Status/entry can read a third, narrower
+ * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
+ * individually readable even though they're only mutated as a pair.
+ *
+ * Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
+ * when a flag changes) rather than re-implementing cache-write logic. Registered on the root
+ * router so it is not team-nested; staff act on teams they do not belong to.
+ */
+export const featureFlagsStaffCacheClearCreateBodyTeamIdsMax = 50
+
+export const FeatureFlagsStaffCacheClearCreateBody = /* @__PURE__ */ zod.object({
+ team_ids: zod
+ .array(zod.number())
+ .max(featureFlagsStaffCacheClearCreateBodyTeamIdsMax)
+ .describe('Team ids to act on (max 50 per request).'),
+ caches: zod
+ .array(
+ zod
+ .enum(['evaluation', 'definitions'])
+ .describe('\* `evaluation` - evaluation\n\* `definitions` - definitions')
+ )
+ .default([`evaluation`, `definitions`])
+ .describe(
+ "Which logical caches to act on: 'evaluation' (the \/flags cache) and\/or 'definitions' (the \/flags\/definitions local-eval cache). Defaults to both."
+ ),
+})
+
+/**
+ * Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
+ *
+ * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
+ * or clears both definitions-cache variants together). Status/entry can read a third, narrower
+ * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
+ * individually readable even though they're only mutated as a pair.
+ *
+ * Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
+ * when a flag changes) rather than re-implementing cache-write logic. Registered on the root
+ * router so it is not team-nested; staff act on teams they do not belong to.
+ */
+export const featureFlagsStaffCacheRebuildCreateBodyTeamIdsMax = 50
+
+export const FeatureFlagsStaffCacheRebuildCreateBody = /* @__PURE__ */ zod.object({
+ team_ids: zod
+ .array(zod.number())
+ .max(featureFlagsStaffCacheRebuildCreateBodyTeamIdsMax)
+ .describe('Team ids to act on (max 50 per request).'),
+ caches: zod
+ .array(
+ zod
+ .enum(['evaluation', 'definitions'])
+ .describe('\* `evaluation` - evaluation\n\* `definitions` - definitions')
+ )
+ .default([`evaluation`, `definitions`])
+ .describe(
+ "Which logical caches to act on: 'evaluation' (the \/flags cache) and\/or 'definitions' (the \/flags\/definitions local-eval cache). Defaults to both."
+ ),
+})
+
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
new file mode 100644
index 000000000000..f54e8866d7f5
--- /dev/null
+++ b/products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene.tsx
@@ -0,0 +1,43 @@
+import { useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { AccessDenied } from 'lib/components/AccessDenied'
+import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { featureFlagsStaffToolsLogic } from './featureFlagsStaffToolsLogic'
+import { StaffCacheToolsTab } from './StaffCacheToolsTab'
+
+export const scene: SceneExport = {
+ component: FeatureFlagsStaffToolsScene,
+ logic: featureFlagsStaffToolsLogic,
+}
+
+export function FeatureFlagsStaffToolsScene(): JSX.Element {
+ const { user } = useValues(userLogic)
+
+ if (!user?.is_staff) {
+ return <AccessDenied object="page" reason="This page is only accessible to staff users." />
+ }
+
+ return (
+ <SceneContent>
+ <SceneTitleSection
+ name="Flags staff tools"
+ description="Look up any team across all organizations to inspect and rebuild its flag caches."
+ resourceType={{ type: 'feature_flag' }}
+ actions={
+ <LemonButton type="secondary" size="small" to={urls.instanceSettings()}>
+ Flags-related instance settings
+ </LemonButton>
+ }
+ />
+ <StaffCacheToolsTab />
+ </SceneContent>
+ )
+}
diff --git a/products/feature_flags/frontend/staff/StaffCacheEntryModal.tsx b/products/feature_flags/frontend/staff/StaffCacheEntryModal.tsx
new file mode 100644
index 000000000000..323e46fc1f3f
--- /dev/null
+++ b/products/feature_flags/frontend/staff/StaffCacheEntryModal.tsx
@@ -0,0 +1,78 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { IconCopy, IconSearch } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonModal, LemonTag, Spinner } from '@posthog/lemon-ui'
+
+import { HighlightedJSONViewer } from 'lib/components/HighlightedJSONViewer'
+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+import { CACHE_LABELS, featureFlagsStaffToolsLogic } from './featureFlagsStaffToolsLogic'
+
+const SEARCH_DEBOUNCE_MS = 300
+
+export function StaffCacheEntryModal(): JSX.Element {
+ const { viewingCacheEntry, cacheEntry, cacheEntryLoading } = useValues(featureFlagsStaffToolsLogic)
+ const { closeCacheEntryModal } = useActions(featureFlagsStaffToolsLogic)
+
+ const [searchValue, setSearchValue] = useState('')
+ const searchQuery = useDebouncedValue(searchValue, SEARCH_DEBOUNCE_MS)
+
+ // Clear the search whenever a different entry is opened (or the modal closes).
+ useEffect(() => {
+ setSearchValue('')
+ }, [viewingCacheEntry?.teamId, viewingCacheEntry?.cache])
+
+ return (
+ <LemonModal
+ title={
+ viewingCacheEntry ? `${CACHE_LABELS[viewingCacheEntry.cache]} - team #${viewingCacheEntry.teamId}` : ''
+ }
+ isOpen={!!viewingCacheEntry}
+ onClose={closeCacheEntryModal}
+ width={720}
+ >
+ {!cacheEntryLoading && cacheEntry?.data ? (
+ <div className="flex items-center gap-2 mb-2">
+ <LemonInput
+ placeholder="Search…"
+ prefix={<IconSearch />}
+ value={searchValue}
+ onChange={setSearchValue}
+ size="small"
+ className="flex-1"
+ data-attr="staff-cache-entry-search"
+ />
+ <LemonButton
+ icon={<IconCopy />}
+ size="small"
+ onClick={() => void copyToClipboard(JSON.stringify(cacheEntry.data, null, 2), 'cache entry')}
+ >
+ Copy
+ </LemonButton>
+ </div>
+ ) : null}
+ <div className="max-h-[70vh] overflow-y-auto">
+ {cacheEntryLoading ? (
+ <div className="flex items-center justify-center">
+ <Spinner className="text-2xl" />
+ </div>
+ ) : cacheEntry?.data ? (
+ <HighlightedJSONViewer
+ src={cacheEntry.data}
+ name={null}
+ collapsed={2}
+ sortKeys={true}
+ searchQuery={searchQuery}
+ />
+ ) : (
+ <div className="flex items-center gap-2">
+ <LemonTag type="warning">Miss</LemonTag>
+ <span className="text-secondary">Nothing is cached in Redis for this team.</span>
+ </div>
+ )}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
new file mode 100644
index 000000000000..2b5404e67b0b
--- /dev/null
+++ b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
@@ -0,0 +1,160 @@
+import { useActions, useValues } from 'kea'
+
+import { IconEye } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonTable, LemonTableColumns, LemonTag } from '@posthog/lemon-ui'
+
+import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
+import { truncate } from 'lib/utils/strings'
+
+import {
+ CACHE_LABELS,
+ featureFlagsStaffToolsLogic,
+ StaffCacheEntryStatus,
+ StaffCacheKind,
+ StaffReadableCacheKind,
+ StaffTeamResult,
+} from './featureFlagsStaffToolsLogic'
+import { StaffCacheEntryModal } from './StaffCacheEntryModal'
+import { StaffTeamSearchInput } from './StaffTeamSearchInput'
+
+const NO_SELECTION_REASON = 'Select at least one team'
+
+const ALL_CACHES: StaffCacheKind[] = ['evaluation', 'definitions']
+
+const READABLE_CACHE_KINDS: StaffReadableCacheKind[] = ['evaluation', 'definitions', 'definitions_no_cohorts']
+
+function CacheStatusCell({ status, onView }: { status?: StaffCacheEntryStatus; onView: () => void }): JSX.Element {
+ const tag = !status ? (
+ <LemonTag type="muted">Unknown</LemonTag>
+ ) : status.source !== 'redis' ? (
+ <LemonTag type="warning">Miss</LemonTag>
+ ) : (
+ <>
+ <LemonTag type="success">Redis</LemonTag>
+ <span className="text-secondary">{status.flag_count} flags</span>
+ </>
+ )
+ return (
+ <span className="flex items-center gap-2">
+ {tag}
+ <LemonButton size="small" icon={<IconEye />} onClick={onView} tooltip="View cache entry" noPadding />
+ </span>
+ )
+}
+
+export function StaffCacheToolsTab(): JSX.Element {
+ const {
+ selectedTeams,
+ selectedTeamIds,
+ cacheStatusByTeamId,
+ cacheStatusLoading,
+ rebuildResultLoading,
+ clearResultLoading,
+ } = useValues(featureFlagsStaffToolsLogic)
+ const { rebuildCache, clearCache, loadCacheStatus, viewCacheEntry } = useActions(featureFlagsStaffToolsLogic)
+
+ const hasSelection = selectedTeamIds.length > 0
+ const mutating = rebuildResultLoading || clearResultLoading
+ const disabledReason = !hasSelection ? NO_SELECTION_REASON : mutating ? 'Action in progress' : undefined
+
+ const columns: LemonTableColumns<StaffTeamResult> = [
+ {
+ title: 'Team',
+ key: 'team',
+ render: (_, team) => (
+ <span>
+ {team.name} <span className="text-secondary">(#{team.id})</span>
+ </span>
+ ),
+ },
+ {
+ title: 'Organization',
+ dataIndex: 'organization_name',
+ },
+ {
+ title: 'Project token',
+ dataIndex: 'api_token',
+ render: (token) => (
+ <CopyToClipboardInline
+ explicitValue={String(token)}
+ description="project token"
+ tooltipMessage="Copy project token"
+ iconSize="xsmall"
+ className="font-mono text-xs"
+ >
+ {truncate(String(token), 16)}
+ </CopyToClipboardInline>
+ ),
+ },
+ ...READABLE_CACHE_KINDS.map((cacheKind) => ({
+ title: CACHE_LABELS[cacheKind],
+ key: cacheKind,
+ render: (_: unknown, team: StaffTeamResult) => (
+ <CacheStatusCell
+ status={cacheStatusByTeamId[team.id]?.[cacheKind]}
+ onView={() => viewCacheEntry({ teamId: team.id, cache: cacheKind })}
+ />
+ ),
+ })),
+ ]
+
+ return (
+ <div className="space-y-4">
+ <StaffTeamSearchInput />
+
+ <div className="flex flex-wrap items-center gap-2 mt-2">
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={() => rebuildCache({ caches: ALL_CACHES })}
+ disabledReason={disabledReason}
+ loading={rebuildResultLoading}
+ >
+ Rebuild flag caches
+ </LemonButton>
+ <LemonButton
+ status="danger"
+ type="secondary"
+ size="small"
+ onClick={() =>
+ LemonDialog.open({
+ title: 'Clear flag caches?',
+ description: `This immediately clears the evaluation and definitions caches in Redis for ${selectedTeamIds.length} selected team(s). Reads will fall through to the database until the caches are rebuilt.`,
+ primaryButton: {
+ children: 'Clear flag caches',
+ status: 'danger',
+ onClick: () => clearCache({ caches: ALL_CACHES }),
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ },
+ })
+ }
+ disabledReason={disabledReason}
+ loading={clearResultLoading}
+ >
+ Clear flag caches
+ </LemonButton>
+ <LemonButton
+ type="tertiary"
+ size="small"
+ onClick={() => loadCacheStatus()}
+ disabledReason={!hasSelection ? NO_SELECTION_REASON : undefined}
+ className="ml-auto"
+ >
+ Refresh status
+ </LemonButton>
+ </div>
+
+ <LemonTable
+ dataSource={selectedTeams}
+ columns={columns}
+ loading={cacheStatusLoading}
+ rowKey={(team) => team.id}
+ emptyState="Search for and select one or more teams to inspect and rebuild their flag caches."
+ />
+
+ <StaffCacheEntryModal />
+ </div>
+ )
+}
diff --git a/products/feature_flags/frontend/staff/StaffTeamSearchInput.tsx b/products/feature_flags/frontend/staff/StaffTeamSearchInput.tsx
new file mode 100644
index 000000000000..cc67b4061553
--- /dev/null
+++ b/products/feature_flags/frontend/staff/StaffTeamSearchInput.tsx
@@ -0,0 +1,43 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { LemonInputSelect, LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+
+import { featureFlagsStaffToolsLogic, StaffTeamResult } from './featureFlagsStaffToolsLogic'
+
+function teamOption(team: StaffTeamResult): LemonInputSelectOption<number> {
+ return {
+ key: String(team.id),
+ value: team.id,
+ label: `${team.name} (#${team.id}) - ${team.organization_name}`,
+ }
+}
+
+export function StaffTeamSearchInput(): JSX.Element {
+ const { teamSearchResults, teamSearchResultsLoading, selectedTeamIds, selectedTeams } =
+ useValues(featureFlagsStaffToolsLogic)
+ const { searchTeams, setSelectedTeamIds } = useActions(featureFlagsStaffToolsLogic)
+
+ // Include already-selected teams so their chips keep a readable label even after the
+ // search results that surfaced them are gone.
+ const options = useMemo(() => {
+ const optionsById = new Map<number, LemonInputSelectOption<number>>()
+ for (const team of [...selectedTeams, ...teamSearchResults]) {
+ optionsById.set(team.id, teamOption(team))
+ }
+ return Array.from(optionsById.values())
+ }, [selectedTeams, teamSearchResults])
+
+ return (
+ <LemonInputSelect<number>
+ mode="multiple"
+ placeholder="Search teams by name, id, project token, or organization"
+ value={selectedTeamIds}
+ options={options}
+ loading={teamSearchResultsLoading}
+ onInputChange={(query) => searchTeams({ query })}
+ onChange={(teamIds) => setSelectedTeamIds(teamIds)}
+ disableFiltering
+ />
+ )
+}
diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
new file mode 100644
index 000000000000..6f343199ef2f
--- /dev/null
+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
@@ -0,0 +1,213 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { featureFlagsStaffToolsLogic, StaffTeamResult } from './featureFlagsStaffToolsLogic'
+
+jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
+ lemonToast: { success: jest.fn(), warning: jest.fn(), error: jest.fn() },
+}))
+
+const TEAM: StaffTeamResult = {
+ id: 5,
+ name: 'Acme',
+ api_token: 'phc_acme',
+ organization_id: 'org-uuid',
+ organization_name: 'Acme Org',
+ project_id: 5,
+}
+
+describe('featureFlagsStaffToolsLogic', () => {
+ let logic: ReturnType<typeof featureFlagsStaffToolsLogic.build>
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ useMocks({
+ get: {
+ '/api/feature_flags_staff_teams': { results: [TEAM] },
+ '/api/feature_flags_staff_cache': { results: [] },
+ },
+ })
+ initKeaTests()
+ logic = featureFlagsStaffToolsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ describe('team-admin deep link', () => {
+ it('seeds and resolves a team from the team-admin deep link', async () => {
+ router.actions.push('/feature_flags/staff?team_id=5')
+ await expectLogic(logic).toDispatchActions(['seedTeamFromDeepLink', 'searchTeams', 'searchTeamsSuccess'])
+ await expectLogic(logic).toMatchValues({
+ selectedTeamIds: [5],
+ selectedTeams: [TEAM],
+ })
+ })
+
+ it('loads cache status for the deep-linked team without a manual refresh', async () => {
+ useMocks({
+ get: {
+ '/api/feature_flags_staff_teams': { results: [TEAM] },
+ '/api/feature_flags_staff_cache': {
+ results: [
+ {
+ team_id: 5,
+ evaluation: { source: 'redis', flag_count: 3 },
+ definitions: { source: 'redis', flag_count: 3 },
+ definitions_no_cohorts: { source: 'miss', flag_count: null },
+ },
+ ],
+ },
+ },
+ })
+
+ router.actions.push('/feature_flags/staff?team_id=5')
+ await expectLogic(logic).toDispatchActions(['seedTeamFromDeepLink', 'loadCacheStatusSuccess'])
+ await expectLogic(logic).toMatchValues({
+ cacheStatusByTeamId: {
+ 5: {
+ team_id: 5,
+ evaluation: { source: 'redis', flag_count: 3 },
+ definitions: { source: 'redis', flag_count: 3 },
+ definitions_no_cohorts: { source: 'miss', flag_count: null },
+ },
+ },
+ })
+ })
+
+ it('does not re-seed a team after it has been manually deselected', async () => {
+ router.actions.push('/feature_flags/staff?team_id=5')
+ await expectLogic(logic).toDispatchActions(['seedTeamFromDeepLink', 'searchTeamsSuccess'])
+
+ logic.actions.setSelectedTeamIds([])
+ // Simulates urlToAction re-running with the same URL, e.g. browser back/forward.
+ router.actions.push('/feature_flags/staff?team_id=5')
+
+ await expectLogic(logic).toMatchValues({ selectedTeamIds: [] })
+ })
+ })
+
+ describe('cache mutations', () => {
+ const MUTATION_CASES = [
+ {
+ label: 'rebuildCache',
+ run: () => logic.actions.rebuildCache({ caches: ['evaluation'] }),
+ url: '/api/feature_flags_staff_cache/rebuild',
+ successAction: 'rebuildCacheSuccess',
+ failureAction: 'rebuildCacheFailure',
+ },
+ {
+ label: 'clearCache',
+ run: () => logic.actions.clearCache({ caches: ['evaluation'] }),
+ url: '/api/feature_flags_staff_cache/clear',
+ successAction: 'clearCacheSuccess',
+ failureAction: 'clearCacheFailure',
+ },
+ ]
+
+ beforeEach(() => {
+ logic.actions.setSelectedTeamIds([5])
+ })
+
+ it.each(MUTATION_CASES)(
+ '$label shows a success toast and reloads status when nothing is missing',
+ async ({ run, url, successAction }) => {
+ useMocks({ post: { [url]: { not_found_team_ids: [] } } })
+
+ run()
+ await expectLogic(logic).toDispatchActions([successAction, 'loadCacheStatus'])
+ expect(lemonToast.success).toHaveBeenCalled()
+ expect(lemonToast.warning).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(MUTATION_CASES)(
+ '$label shows a warning toast when some team ids are not found',
+ async ({ run, url, successAction }) => {
+ useMocks({ post: { [url]: { not_found_team_ids: [999] } } })
+
+ run()
+ await expectLogic(logic).toDispatchActions([successAction, 'loadCacheStatus'])
+ expect(lemonToast.warning).toHaveBeenCalled()
+ expect(lemonToast.success).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(MUTATION_CASES)('$label shows an error toast on failure', async ({ run, url, failureAction }) => {
+ useMocks({ post: { [url]: () => [500, {}] } })
+
+ run()
+ await expectLogic(logic).toDispatchActions([failureAction])
+ expect(lemonToast.error).toHaveBeenCalled()
+ })
+ })
+
+ describe('cache entry viewer', () => {
+ it('fetches the entry for the requested team and cache, keyed by team_id and cache', async () => {
+ useMocks({
+ get: {
+ '/api/feature_flags_staff_cache/entry': ({ request }) => {
+ const params = new URL(request.url).searchParams
+ return [
+ 200,
+ {
+ team_id: Number(params.get('team_id')),
+ cache: params.get('cache'),
+ source: 'redis',
+ data: { flags: [] },
+ },
+ ]
+ },
+ },
+ })
+
+ logic.actions.viewCacheEntry({ teamId: 5, cache: 'definitions' })
+ await expectLogic(logic)
+ .toDispatchActions(['viewCacheEntrySuccess'])
+ .toMatchValues({
+ viewingCacheEntry: { teamId: 5, cache: 'definitions' },
+ cacheEntry: { team_id: 5, cache: 'definitions', source: 'redis', data: { flags: [] } },
+ })
+ })
+
+ it('clears the viewed entry on close', async () => {
+ useMocks({ get: { '/api/feature_flags_staff_cache/entry': { team_id: 5, cache: 'evaluation' } } })
+
+ logic.actions.viewCacheEntry({ teamId: 5, cache: 'evaluation' })
+ await expectLogic(logic).toDispatchActions(['viewCacheEntrySuccess'])
+
+ logic.actions.closeCacheEntryModal()
+ expectLogic(logic).toMatchValues({ viewingCacheEntry: null })
+ })
+
+ it('shows an error toast and closes the modal on failure', async () => {
+ useMocks({ get: { '/api/feature_flags_staff_cache/entry': () => [404, {}] } })
+
+ logic.actions.viewCacheEntry({ teamId: 5, cache: 'evaluation' })
+ await expectLogic(logic).toDispatchActions(['viewCacheEntryFailure'])
+ expect(lemonToast.error).toHaveBeenCalled()
+ expectLogic(logic).toMatchValues({ viewingCacheEntry: null })
+ })
+ })
+
+ describe('team search loader', () => {
+ it('does not query below the minimum search length', async () => {
+ logic.actions.searchTeams({ query: 'a' })
+ await expectLogic(logic).toDispatchActions(['searchTeamsSuccess']).toMatchValues({ teamSearchResults: [] })
+ })
+
+ it('returns results and records display info for a real query', async () => {
+ logic.actions.searchTeams({ query: 'Acme' })
+ await expectLogic(logic)
+ .toDispatchActions(['searchTeamsSuccess'])
+ .toMatchValues({ teamSearchResults: [TEAM], knownTeams: { 5: TEAM } })
+ })
+ })
+})
diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
new file mode 100644
index 000000000000..c0ff2203cfe3
--- /dev/null
+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
@@ -0,0 +1,229 @@
+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,
+ featureFlagsStaffCacheRebuildCreate,
+ featureFlagsStaffTeamsList,
+} from '../generated/api'
+import type {
+ CachesEnumApi,
+ FeatureFlagsStaffCacheEntryRetrieveCache,
+ StaffCacheEntryResponseApi,
+ StaffCacheMutationResponseApi,
+ StaffCacheTeamStatusApi,
+ StaffTeamResultApi,
+} from '../generated/api.schemas'
+import type { featureFlagsStaffToolsLogicType } from './featureFlagsStaffToolsLogicType'
+
+// What rebuild/clear can act on. Mirrors the backend's CACHE_CHOICES.
+export type StaffCacheKind = CachesEnumApi
+
+// What status/entry can read. Mirrors the backend's READABLE_CACHE_CHOICES: unlike mutation,
+// the two definitions-cache variants are individually observable even though they're only
+// mutated as a pair (see the backend's staff_cache.py module docstring).
+export type StaffReadableCacheKind = FeatureFlagsStaffCacheEntryRetrieveCache
+
+export const CACHE_LABELS: Record<StaffReadableCacheKind, string> = {
+ evaluation: 'Flags cache',
+ definitions: 'Definitions cache (cohorts)',
+ definitions_no_cohorts: 'Definitions cache (no cohorts)',
+}
+
+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 const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>([
+ path(['products', 'feature_flags', 'frontend', 'staff', 'featureFlagsStaffToolsLogic']),
+ actions({
+ setSelectedTeamIds: (teamIds: number[]) => ({ teamIds }),
+ seedTeamFromDeepLink: (teamId: number) => ({ teamId }),
+ closeCacheEntryModal: true,
+ }),
+ loaders(({ values }) => ({
+ teamSearchResults: [
+ [] as StaffTeamResult[],
+ {
+ searchTeams: async ({ query }: { query: string }, breakpoint) => {
+ const trimmed = query.trim()
+ // Digit-only queries are exact team-id lookups (allowed at one digit so
+ // deep links to low-id teams resolve); other queries need >= 2 chars.
+ const minLength = /^\d+$/.test(trimmed) ? 1 : MIN_SEARCH_LENGTH
+ if (trimmed.length < minLength) {
+ return []
+ }
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ const response = await featureFlagsStaffTeamsList({ search: query })
+ breakpoint()
+ return response.results
+ },
+ },
+ ],
+ cacheStatus: [
+ [] as StaffCacheTeamStatus[],
+ {
+ loadCacheStatus: async (_: void, breakpoint) => {
+ const teamIds = values.selectedTeamIds
+ if (teamIds.length === 0) {
+ return []
+ }
+ // Debounce so selecting several teams in quick succession collapses into one
+ // 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)}`
+ )
+ breakpoint()
+ return response.results
+ },
+ },
+ ],
+ rebuildResult: [
+ null as StaffCacheMutationResponse | null,
+ {
+ rebuildCache: async ({ caches }: { caches: StaffCacheKind[] }) => {
+ return await featureFlagsStaffCacheRebuildCreate({ team_ids: values.selectedTeamIds, caches })
+ },
+ },
+ ],
+ clearResult: [
+ null as StaffCacheMutationResponse | null,
+ {
+ clearCache: async ({ caches }: { caches: StaffCacheKind[] }) => {
+ return await featureFlagsStaffCacheClearCreate({ team_ids: values.selectedTeamIds, caches })
+ },
+ },
+ ],
+ cacheEntry: [
+ null as StaffCacheEntry | null,
+ {
+ viewCacheEntry: async ({ teamId, cache }: { teamId: number; cache: StaffReadableCacheKind }) => {
+ return await featureFlagsStaffCacheEntryRetrieve({ team_id: teamId, cache })
+ },
+ },
+ ],
+ })),
+ reducers({
+ selectedTeamIds: [
+ [] as number[],
+ {
+ setSelectedTeamIds: (_, { teamIds }) => teamIds,
+ seedTeamFromDeepLink: (state, { teamId }) => (state.includes(teamId) ? state : [...state, teamId]),
+ },
+ ],
+ // Accumulate team display info (name/org/token) from every search so the
+ // selected-teams table can render more than a bare id, even for teams no
+ // longer in the latest search results.
+ knownTeams: [
+ {} as Record<number, StaffTeamResult>,
+ {
+ searchTeamsSuccess: (state, { teamSearchResults }) => ({
+ ...state,
+ ...Object.fromEntries(teamSearchResults.map((team) => [team.id, team])),
+ }),
+ },
+ ],
+ // Seeds only once per mount so manually deselecting a deep-linked team doesn't
+ // bring it back if urlToAction re-runs later (e.g. browser back/forward).
+ hasSeededFromDeepLink: [
+ false,
+ {
+ seedTeamFromDeepLink: () => true,
+ },
+ ],
+ viewingCacheEntry: [
+ null as { teamId: number; cache: StaffReadableCacheKind } | null,
+ {
+ viewCacheEntry: (_, { teamId, cache }) => ({ teamId, cache }),
+ closeCacheEntryModal: () => null,
+ },
+ ],
+ }),
+ selectors({
+ selectedTeams: [
+ (s) => [s.selectedTeamIds, s.knownTeams],
+ (selectedTeamIds: number[], knownTeams: Record<number, StaffTeamResult>): StaffTeamResult[] =>
+ selectedTeamIds.map((id) => knownTeams[id]).filter(Boolean),
+ ],
+ cacheStatusByTeamId: [
+ (s) => [s.cacheStatus],
+ (cacheStatus: StaffCacheTeamStatus[]): Record<number, StaffCacheTeamStatus> =>
+ Object.fromEntries(cacheStatus.map((status) => [status.team_id, status])),
+ ],
+ }),
+ listeners(({ actions }) => {
+ const onMutationSuccess = (
+ result: StaffCacheMutationResponse | null,
+ doneMessage: string,
+ partialLabel: string
+ ): void => {
+ const notFound = result?.not_found_team_ids ?? []
+ if (notFound.length > 0) {
+ lemonToast.warning(`${partialLabel}, but some team ids were not found: ${notFound.join(', ')}`)
+ } else {
+ lemonToast.success(doneMessage)
+ }
+ actions.loadCacheStatus()
+ }
+
+ return {
+ setSelectedTeamIds: () => {
+ actions.loadCacheStatus()
+ },
+ seedTeamFromDeepLink: ({ teamId }) => {
+ actions.searchTeams({ query: String(teamId) })
+ actions.loadCacheStatus()
+ },
+ rebuildCacheSuccess: ({ rebuildResult }) => {
+ onMutationSuccess(
+ rebuildResult,
+ 'Flag caches rebuild queued. Re-check status in a few seconds.',
+ 'Rebuild queued'
+ )
+ },
+ rebuildCacheFailure: () => {
+ lemonToast.error('Failed to queue flag caches rebuild.')
+ },
+ clearCacheSuccess: ({ clearResult }) => {
+ onMutationSuccess(clearResult, 'Cache clear queued. Re-check status in a few seconds.', 'Clear queued')
+ },
+ clearCacheFailure: () => {
+ lemonToast.error('Failed to clear cache.')
+ },
+ viewCacheEntryFailure: () => {
+ lemonToast.error('Failed to load cache entry.')
+ actions.closeCacheEntryModal()
+ },
+ }
+ }),
+ urlToAction(({ actions, values }) => ({
+ '/feature_flags/staff': (_, searchParams) => {
+ // Team-admin deep link: seed the selected team and resolve its display info
+ // (exact id search hits the endpoint's Q(id=...) branch). Seeds only once per
+ // mount so manually deselecting the team doesn't bring it back if this handler
+ // re-runs later (e.g. browser back/forward).
+ const teamId = searchParams.team_id ? Number(searchParams.team_id) : null
+ if (teamId && !values.hasSeededFromDeepLink) {
+ actions.seedTeamFromDeepLink(teamId)
+ }
+ },
+ })),
+])
diff --git a/products/feature_flags/manifest.tsx b/products/feature_flags/manifest.tsx
index 61192dd79abe..ef3e4c40fb53 100644
--- a/products/feature_flags/manifest.tsx
+++ b/products/feature_flags/manifest.tsx
@@ -12,14 +12,22 @@ export const manifest: ProductManifest = {
projectBased: true,
name: 'Feature flag templates',
},
+ FeatureFlagsStaffTools: {
+ import: () => import('./frontend/staff/FeatureFlagsStaffToolsScene'),
+ instanceLevel: true,
+ name: 'Flags staff tools',
+ },
},
routes: {
'/feature_flags/templates': ['FeatureFlagTemplates', 'featureFlagTemplates'],
+ '/feature_flags/staff': ['FeatureFlagsStaffTools', 'featureFlagsStaffTools'],
},
urls: {
featureFlag: (id: string | number): string => `/feature_flags/${id}`,
featureFlags: (tab?: string): string => `/feature_flags${tab ? `?tab=${tab}` : ''}`,
featureFlagTemplates: (): string => '/feature_flags/templates',
+ featureFlagsStaffTools: (teamId?: number): string =>
+ `/feature_flags/staff${teamId ? `?team_id=${teamId}` : ''}`,
featureFlagNew: ({
type,
sourceId,
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index c4a4cd4794f7..c4c4198afc52 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -273,6 +273,21 @@ tools:
feature-flags-remote-config-retrieve:
operation: feature_flags_remote_config_retrieve
enabled: false
+ feature-flags-staff-cache-clear-create:
+ operation: feature_flags_staff_cache_clear_create
+ enabled: false
+ feature-flags-staff-cache-entry-retrieve:
+ operation: feature_flags_staff_cache_entry_retrieve
+ enabled: false
+ feature-flags-staff-cache-list:
+ operation: feature_flags_staff_cache_list
+ enabled: false
+ feature-flags-staff-cache-rebuild-create:
+ operation: feature_flags_staff_cache_rebuild_create
+ enabled: false
+ feature-flags-staff-teams-list:
+ operation: feature_flags_staff_teams_list
+ enabled: false
feature-flags-status-retrieve:
operation: feature_flags_status_retrieve
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 80e7460a6384..7b780789c574 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12224,6 +12224,32 @@ export namespace Schemas {
failing_workflows?: string[];
}
+ /**
+ * * `evaluation` - evaluation
+ * * `definitions` - definitions
+ * * `definitions_no_cohorts` - definitions_no_cohorts
+ */
+ export type CacheEnum = typeof CacheEnum[keyof typeof CacheEnum];
+
+
+ export const CacheEnum = {
+ Evaluation: 'evaluation',
+ Definitions: 'definitions',
+ DefinitionsNoCohorts: 'definitions_no_cohorts',
+ } as const;
+
+ /**
+ * * `evaluation` - evaluation
+ * * `definitions` - definitions
+ */
+ export type CachesEnum = typeof CachesEnum[keyof typeof CachesEnum];
+
+
+ export const CachesEnum = {
+ Evaluation: 'evaluation',
+ Definitions: 'definitions',
+ } as const;
+
export interface EventsHeatMapColumnAggregationResult {
column: number;
value: number;
@@ -52594,6 +52620,111 @@ export namespace Schemas {
Service: 'service',
} as const;
+ /**
+ * Raw cached payload as stored in Redis, or null on a miss.
+ * @nullable
+ */
+ export type StaffCacheEntryResponseData = { [key: string]: unknown } | null;
+
+ /**
+ * * `redis` - redis
+ * * `miss` - miss
+ */
+ export type StaffCacheSourceEnum = typeof StaffCacheSourceEnum[keyof typeof StaffCacheSourceEnum];
+
+
+ export const StaffCacheSourceEnum = {
+ Redis: 'redis',
+ Miss: 'miss',
+ } as const;
+
+ export interface StaffCacheEntryResponse {
+ /** Team id. */
+ team_id: number;
+ /** Which cache this entry is for.
+ *
+ * * `evaluation` - evaluation
+ * * `definitions` - definitions
+ * * `definitions_no_cohorts` - definitions_no_cohorts */
+ cache: CacheEnum;
+ /** 'redis' when a warm entry is cached, or 'miss' when nothing is cached in Redis.
+ *
+ * * `redis` - redis
+ * * `miss` - miss */
+ source: StaffCacheSourceEnum;
+ /**
+ * Raw cached payload as stored in Redis, or null on a miss.
+ * @nullable
+ */
+ data: StaffCacheEntryResponseData;
+ }
+
+ export interface StaffCacheEntryStatus {
+ /** 'redis' when a warm entry is cached, or 'miss' when nothing is cached in Redis.
+ *
+ * * `redis` - redis
+ * * `miss` - miss */
+ source: StaffCacheSourceEnum;
+ /**
+ * Number of flags in the cached payload, or null on a miss.
+ * @nullable
+ */
+ flag_count: number | null;
+ }
+
+ export interface StaffCacheMutation {
+ /**
+ * Team ids to act on (max 50 per request).
+ * @maxItems 50
+ */
+ team_ids: number[];
+ /** Which logical caches to act on: 'evaluation' (the /flags cache) and/or 'definitions' (the /flags/definitions local-eval cache). Defaults to both. */
+ caches?: CachesEnum[];
+ }
+
+ export interface StaffCacheMutationResponse {
+ /** Team ids for which the requested action's tasks were enqueued. */
+ queued_team_ids: number[];
+ /** Requested team ids that do not exist. */
+ not_found_team_ids: number[];
+ }
+
+ export interface StaffCacheTeamStatus {
+ /** Team id. */
+ team_id: number;
+ /** Status of the /flags evaluation cache. */
+ evaluation: StaffCacheEntryStatus;
+ /** Status of the /flags/definitions local-eval cache (with-cohorts variant). */
+ definitions: StaffCacheEntryStatus;
+ /** Status of the /flags/definitions local-eval cache (without-cohorts variant, cohort filters transformed to properties for simple SDK clients). */
+ definitions_no_cohorts: StaffCacheEntryStatus;
+ }
+
+ export interface StaffCacheStatusResponse {
+ /** Per-team cache status. */
+ results: StaffCacheTeamStatus[];
+ }
+
+ export interface StaffTeamResult {
+ /** Team id. */
+ id: number;
+ /** Team name. */
+ name: string;
+ /** Team api_token (used as the flags evaluation cache key). */
+ api_token: string;
+ /** Organization uuid that owns the team. */
+ organization_id: string;
+ /** Organization name that owns the team. */
+ organization_name: string;
+ /** Project id the team belongs to. */
+ project_id: number;
+ }
+
+ export interface StaffTeamSearchResponse {
+ /** Matching teams. */
+ results: StaffTeamResult[];
+ }
+
/**
* Response containing a JWT token (and resolved base URL) for reading a task run's live event stream
*/
@@ -61664,6 +61795,53 @@ export namespace Schemas {
export type EnvironmentsWebVitalsRetrieve200 = { [key: string]: unknown };
+ 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.
+ * @maxItems 50
+ */
+ team_ids: number[];
+ };
+
+ export type FeatureFlagsStaffCacheEntryRetrieveParams = {
+ /**
+ * Which cache to fetch: 'evaluation' (the /flags cache), 'definitions' (the /flags/definitions local-eval cache, with-cohorts variant), or 'definitions_no_cohorts' (the without-cohorts variant served to simple SDK clients).
+ *
+ * * `evaluation` - evaluation
+ * * `definitions` - definitions
+ * * `definitions_no_cohorts` - definitions_no_cohorts
+ * @minLength 1
+ */
+ cache: FeatureFlagsStaffCacheEntryRetrieveCache;
+ /**
+ * Team id to fetch the cache entry for.
+ */
+ team_id: number;
+ };
+
+ export type FeatureFlagsStaffCacheEntryRetrieveCache = typeof FeatureFlagsStaffCacheEntryRetrieveCache[keyof typeof FeatureFlagsStaffCacheEntryRetrieveCache];
+
+
+ export const FeatureFlagsStaffCacheEntryRetrieveCache = {
+ Evaluation: 'evaluation',
+ Definitions: 'definitions',
+ DefinitionsNoCohorts: 'definitions_no_cohorts',
+ } as const;
+
+ export type FeatureFlagsStaffTeamsListParams = {
+ /**
+ * Maximum number of teams to return (default 25, max 100).
+ * @minimum 1
+ * @maximum 100
+ */
+ 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.
+ * @minLength 1
+ */
+ search: string;
+ };
+
export type LlmAnalyticsPersonalSpendListParams = {
/**
* Start of the spend window. Accepts absolute dates (`2026-04-23`) or relative strings (`-7d`, `-1m`, etc.) — same parser used elsewhere in PostHog. Defaults to `-30d`. The window between `date_from` and `date_to` cannot exceed 90 days.