:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cohorts): add staff tools for stuck cohort recalculation (#72468)
Phil Haack8461707ccf27
diff --git a/frontend/src/lib/components/Account/AccountMenu.tsx b/frontend/src/lib/components/Account/AccountMenu.tsxindex fe1eba68a5e0..1e2432a77d40 100644--- a/frontend/src/lib/components/Account/AccountMenu.tsx+++ b/frontend/src/lib/components/Account/AccountMenu.tsx@@ -15,6 +15,7 @@ import {IconLive,IconNight,IconPalette,+ IconPeople,IconPlusSmall,IconReceipt,IconServer,@@ -437,6 +438,18 @@ export function AccountMenu({ trigger, ...props }: AccountMenuProps): JSX.ElemenFlags staff tools</Link></DropdownMenuItem>+ <DropdownMenuItem asChild>+ <Link+ to={urls.cohortsStaffTools()}+ buttonProps={{+ menuItem: true,+ }}+ data-attr="top-menu-cohorts-staff-tools"+ >+ <IconPeople />+ Cohorts 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.tsxindex a05c12aebc70..b01c2d2ef915 100644--- a/frontend/src/lib/components/Account/NewAccountMenu.tsx+++ b/frontend/src/lib/components/Account/NewAccountMenu.tsx@@ -5,6 +5,7 @@ import {IconDatabase,IconGear,IconLeave,+ IconPeople,IconPlusSmall,IconReceipt,IconServer,@@ -399,6 +400,21 @@ export function NewAccountMenu({ isLayoutNavCollapsed }: AccountMenuProps): JSX.</Link>)}/>+ <Menu.Item+ render={(props) => (+ <Link+ {...props}+ to={urls.cohortsStaffTools()}+ buttonProps={{+ menuItem: true,+ }}+ data-attr="new-account-menu-cohorts-staff-tools"+ >+ <IconPeople />+ Cohorts staff tools+ </Link>+ )}+ /><Menu.Itemrender={(props) => (<Linkdiff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 84b191fa8a93..b855f9a28021 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -40,6 +40,7 @@ export const productScenes: Record<string, () => Promise<any>> = {BusinessKnowledge: () => import('../../products/business_knowledge/frontend/scenes/BusinessKnowledgeScene'),Transformations: () => import('../../frontend/src/scenes/data-pipelines/TransformationsScene'),EventFiltering: () => import('../../frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene'),+ CohortsStaffTools: () => import('../../products/cohorts/frontend/staff/CohortsStaffToolsScene'),SupportTickets: () => import('../../products/conversations/frontend/scenes/tickets/SupportTicketsScene'),SupportTicketDetail: () => import('../../products/conversations/frontend/scenes/ticket/SupportTicketScene'),SupportSettings: () => import('../../products/conversations/frontend/scenes/settings/SupportSettingsScene'),diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 0891eaf2d0c3..27ea23eaa82f 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -91,6 +91,7 @@ export const productRoutes: Record<string, [string, string]> = {'/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],'/transformations': ['Transformations', 'transformations'],'/event-filtering': ['EventFiltering', 'eventFiltering'],+ '/cohorts/staff': ['CohortsStaffTools', 'cohortsStaffTools'],'/support/tickets': ['SupportTickets', 'supportTickets'],'/support/tickets/:ticketId': ['SupportTicketDetail', 'supportTicketDetail'],'/support/settings': ['SupportSettings', 'supportSettings'],@@ -512,6 +513,7 @@ export const productConfiguration: Record<string, any> = {description: 'Drop events at ingestion time based on event metadata.',iconType: 'data_pipeline',},+ CohortsStaffTools: { instanceLevel: true, name: 'Cohorts staff tools' },SupportTickets: { name: 'Ticket list', projectBased: true, layout: 'app-container' },SupportTicketDetail: { name: 'Ticket detail', projectBased: true, layout: 'app-container' },SupportSettings: { name: 'Support settings', projectBased: true, layout: 'app-container' },@@ -947,6 +949,7 @@ export const productUrls = {cohort: (id: string | number): string => `/cohorts/${id}`,cohorts: (): string => '/cohorts',cohortCalculationHistory: (id: string | number): string => `/cohorts/${id}/calculation-history`,+ cohortsStaffTools: (cohortId?: number): string => `/cohorts/staff${cohortId ? `?cohort_id=${cohortId}` : ''}`,supportDashboard: (): string => '/support',supportTickets: (): string => '/support/tickets',supportTicketDetail: (ticketId: string | number): string => `/support/tickets/${ticketId}`,diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex f6ff2c4c4c3f..6a0f4dbedc6f 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -831,6 +831,8 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.groupsNew(':groupTypeIndex')]: [Scene.GroupsNew, 'groupsNew'],[urls.group(':groupTypeIndex', ':groupKey', false)]: [Scene.Group, 'group'],[urls.group(':groupTypeIndex', ':groupKey', false, ':groupTab')]: [Scene.Group, 'groupWithTab'],+ // Must precede the cohort detail route, or /cohorts/staff resolves as cohort id "staff".+ [urls.cohortsStaffTools()]: ['CohortsStaffTools' as Scene, 'cohortsStaffTools'],[urls.cohort(':id')]: [Scene.Cohort, 'cohort'],[urls.cohortCalculationHistory(':id')]: [Scene.CohortCalculationHistory, 'cohortCalculationHistory'],[urls.cohorts()]: [Scene.Cohorts, 'cohorts'],diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6ccfcbfbf60e..a67e3c087398 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2851,6 +2851,9 @@ importers:'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected]([email protected]))products/conversations:dependencies:diff --git a/posthog/api/fields.py b/posthog/api/fields.pyindex e40024bbcb6c..15fae220f327 100644--- a/posthog/api/fields.py+++ b/posthog/api/fields.py@@ -5,6 +5,7 @@ reuse them instead of redefining local copies."""import json+from typing import Anyfrom drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializers@@ -27,6 +28,20 @@ class JSONStringFilterField(serializers.JSONField):pass+class RepeatedOrCommaSeparatedListField(serializers.ListField):+ """ListField for query params that accepts values either as repeated keys+ (?ids=1&ids=2) or as a single comma-separated value (?ids=1,2). The latter is how our+ generated TS client (and plain URLSearchParams) serializes a number[] query param, so+ without this a caller using the generated client gets a validation error.+ """++ def get_value(self, dictionary: Any) -> Any:+ value = super().get_value(dictionary)+ if isinstance(value, list) and len(value) == 1 and isinstance(value[0], str) and "," in value[0]:+ return value[0].split(",")+ return value++class JSONTolerantListField(serializers.ListField):"""ListField that also accepts a single JSON-encoded array as the query value.diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex cbb81c55db43..f5303072d10d 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -348,7 +348,12 @@ def enqueue_cohorts_to_calculate(parallel_count: int) -> None:logger.exception("failed_to_update_cohort_metrics", error=str(e))-def increment_version_and_enqueue_calculate_cohort(cohort: Cohort, *, initiating_user: Optional[User]) -> None:+def increment_version_and_enqueue_calculate_cohort(cohort: Cohort, *, initiating_user: Optional[User]) -> bool:+ """+ Returns False if dependency resolution failed and only `cohort` itself was enqueued instead+ of its full dependency chain, so callers that need to (e.g. the staff recalculate endpoint)+ can tell a caller the request wasn't fully honored. Callers that don't care can ignore it.+ """dependent_cohorts = get_all_cohort_dependents(cohort)dependency_cohorts = get_all_cohort_dependencies(cohort)related_cohorts = dependent_cohorts + dependency_cohorts@@ -375,16 +380,18 @@ def increment_version_and_enqueue_calculate_cohort(cohort: Cohort, *, initiating# Fall back to calculating just this cohort without dependencieslogger.warning("cohort_fallback_to_single_calculation", cohort_id=cohort.id)_enqueue_single_cohort_calculation(cohort, initiating_user)- return+ return False# Create a chain of tasks to ensure sequential execution.# Non-first tasks get a 2s countdown to mitigate ClickHouse replica lag:# the preceding cohort's new rows may not have replicated yet. See #47618.task_chain: list = []+ prepared_cohort_ids: list[int] = []for cohort_id in sorted_cohort_ids:current_cohort = seen_cohorts_cache.get(cohort_id)if current_cohort and not current_cohort.is_static:_prepare_cohort_for_calculation(current_cohort)+ prepared_cohort_ids.append(current_cohort.id)task = calculate_cohort_ch.si(current_cohort.id,current_cohort.pending_version,@@ -395,11 +402,20 @@ def increment_version_and_enqueue_calculate_cohort(cohort: Cohort, *, initiatingtask_chain.append(task)if task_chain:- chain(*task_chain).apply_async()+ try:+ chain(*task_chain).apply_async()+ except Exception:+ # apply_async() never actually enqueued anything, but _prepare_cohort_for_calculation+ # already flipped is_calculating on every cohort in the chain. Clear it so they aren't+ # stranded looking "in flight" until the hourly stuck-cohort reset catches them.+ Cohort.objects.filter(id__in=prepared_cohort_ids).update(is_calculating=False)+ raiseelse:logger.info("cohort_has_no_dependencies", cohort_id=cohort.id)_enqueue_single_cohort_calculation(cohort, initiating_user)+ return True+def _prepare_cohort_for_calculation(cohort: Cohort) -> None:"""@@ -421,11 +437,20 @@ def _prepare_cohort_for_calculation(cohort: Cohort) -> None:def _enqueue_single_cohort_calculation(cohort: Cohort, initiating_user: Optional[User]) -> None:"""Helper function to enqueue a single cohort for calculation"""_prepare_cohort_for_calculation(cohort)- calculate_cohort_ch.delay(- cohort.id,- cohort.pending_version,- initiating_user.id if initiating_user else None,- )+ try:+ calculate_cohort_ch.delay(+ cohort.id,+ cohort.pending_version,+ initiating_user.id if initiating_user else None,+ )+ except Exception:+ # .delay() never actually enqueued anything, but _prepare_cohort_for_calculation already+ # flipped is_calculating. Clear it so the cohort isn't stranded looking "in flight" until+ # the hourly stuck-cohort reset catches it.+ if not cohort.is_static:+ cohort.is_calculating = False+ cohort.save(update_fields=["is_calculating"])+ raise@shared_task(diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.pyindex 509e729d51e1..839eafc5c197 100644--- a/posthog/tasks/test/test_calculate_cohort.py+++ b/posthog/tasks/test/test_calculate_cohort.py@@ -1232,3 +1232,46 @@ class TestCohortCalculationTasks(APIBaseTest):mock_chain.assert_called_once()mock_chain_instance.apply_async.assert_called_once()++ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_increment_version_and_enqueue_resets_is_calculating_when_delay_fails(+ self, mock_calculate_cohort_ch_delay: MagicMock+ ) -> None:+ # A broker outage shouldn't strand the cohort looking "in flight": nothing was actually+ # enqueued, so is_calculating must go back to False rather than wait an hour for the+ # stuck-cohort reset to notice.+ cohort = Cohort.objects.create(team=self.team, name="Standalone Cohort", is_static=False)+ mock_calculate_cohort_ch_delay.side_effect = Exception("broker unavailable")++ with self.assertRaises(Exception):+ increment_version_and_enqueue_calculate_cohort(cohort, initiating_user=None)++ cohort.refresh_from_db()+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.pending_version, 1)++ @patch("posthog.tasks.calculate_cohort.chain")+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.si")+ def test_increment_version_and_enqueue_resets_is_calculating_for_chain_when_apply_async_fails(+ self, mock_calculate_cohort_ch_si: MagicMock, mock_chain: MagicMock+ ) -> None:+ # Same as above, but for the dependency-chain path: a mid-chain broker failure must not+ # strand any cohort in the chain, not just the one the caller passed in.+ cohort_a = Cohort.objects.create(team=self.team, name="Cohort A", is_static=False)+ cohort_b = Cohort.objects.create(+ team=self.team,+ name="Cohort B (references A)",+ filters={"properties": {"type": "AND", "values": [{"key": "id", "value": cohort_a.id, "type": "cohort"}]}},+ is_static=False,+ )++ mock_chain.return_value.apply_async.side_effect = Exception("broker unavailable")+ mock_calculate_cohort_ch_si.return_value = MagicMock()++ with self.assertRaises(Exception):+ increment_version_and_enqueue_calculate_cohort(cohort_b, initiating_user=None)++ cohort_a.refresh_from_db()+ cohort_b.refresh_from_db()+ self.assertFalse(cohort_a.is_calculating)+ self.assertFalse(cohort_b.is_calculating)diff --git a/products/cohorts/backend/api/__init__.py b/products/cohorts/backend/api/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cohorts/backend/api/staff_tools.py b/products/cohorts/backend/api/staff_tools.pynew file mode 100644index 000000000000..3115c27457c0--- /dev/null+++ b/products/cohorts/backend/api/staff_tools.py@@ -0,0 +1,263 @@+from typing import Any, cast++import structlog+from drf_spectacular.utils import OpenApiResponse, extend_schema_serializer+from rest_framework import request, response, serializers, status, viewsets+from rest_framework.decorators import action+from rest_framework.permissions import IsAuthenticated++from posthog.api.fields import RepeatedOrCommaSeparatedListField+from posthog.api.mixins import validated_request+from posthog.exceptions_capture import capture_exception+from posthog.helpers.impersonation import is_impersonated+from posthog.models.user import User+from posthog.permissions import IsStaffUser+from posthog.tasks.calculate_cohort import (+ get_stuck_cohort_calculation_candidates_queryset,+ increment_version_and_enqueue_calculate_cohort,+)++from products.cohorts.backend.models.cohort import Cohort++logger = structlog.get_logger(__name__)++MAX_COHORTS_PER_LOOKUP = 50+# Recalculating a cohort fans out into its full dependency chain of ClickHouse calculations,+# so the batch cap is much lower than for the lookup.+MAX_COHORTS_PER_RECALCULATE = 10+MAX_STUCK_COHORTS_LISTED = 100++SKIP_REASON_DELETED = "Cohort is deleted."+SKIP_REASON_STATIC = "Static cohorts are populated once from their source; recalculation is not supported."+++def _cohort_ids_field(help_text: str, *, max_length: int) -> serializers.ListField:+ return RepeatedOrCommaSeparatedListField(+ child=serializers.IntegerField(), min_length=1, max_length=max_length, help_text=help_text+ )+++class StaffCohortLookupQuerySerializer(serializers.Serializer):+ cohort_ids = _cohort_ids_field(+ f"Cohort ids to look up (max {MAX_COHORTS_PER_LOOKUP} per request). Repeat the param "+ "(?cohort_ids=1&cohort_ids=2) or pass one comma-separated value (?cohort_ids=1,2).",+ max_length=MAX_COHORTS_PER_LOOKUP,+ )+++class StaffCohortSerializer(serializers.Serializer):+ id = serializers.IntegerField(help_text="Cohort id.")+ name = serializers.CharField(allow_null=True, help_text="Cohort name.")+ team_id = serializers.IntegerField(help_text="Id of the team the cohort belongs to.")+ team_name = serializers.CharField(source="team.name", help_text="Name of the team the cohort belongs to.")+ project_id = serializers.IntegerField(+ source="team.project_id",+ help_text="Project id the cohort's team belongs to, for building /project/<id>/cohorts/<id> links.",+ )+ deleted = serializers.BooleanField(help_text="Whether the cohort is soft-deleted.")+ is_static = serializers.BooleanField(+ help_text="Whether the cohort is static (populated once from a source rather than recalculated)."+ )+ is_calculating = serializers.BooleanField(help_text="Whether a calculation is currently marked as in flight.")+ last_calculation = serializers.DateTimeField(+ allow_null=True, help_text="When the last calculation completed, or null if never calculated."+ )+ last_calculation_duration_ms = serializers.IntegerField(+ allow_null=True, help_text="Duration of the last completed calculation in milliseconds."+ )+ errors_calculating = serializers.IntegerField(+ help_text="Consecutive calculation failures; above 20 the cohort is excluded from periodic recalculation."+ )+ last_error_at = serializers.DateTimeField(+ allow_null=True, help_text="When the last calculation error was recorded."+ )+ version = serializers.IntegerField(allow_null=True, help_text="Version of the last completed calculation.")+ pending_version = serializers.IntegerField(+ allow_null=True,+ help_text="Version most recently requested; greater than `version` while a calculation is pending or stuck.",+ )+ count = serializers.IntegerField(+ allow_null=True, help_text="Number of persons in the cohort as of the last completed calculation."+ )+ created_at = serializers.DateTimeField(allow_null=True, help_text="When the cohort was created.")+++@extend_schema_serializer(many=False)+class StaffCohortLookupResponseSerializer(serializers.Serializer):+ results = StaffCohortSerializer(many=True, help_text="Requested cohorts, in request order.")+ not_found_cohort_ids = serializers.ListField(+ child=serializers.IntegerField(), help_text="Requested cohort ids that do not exist."+ )+++@extend_schema_serializer(many=False)+class StaffStuckCohortsResponseSerializer(serializers.Serializer):+ results = StaffCohortSerializer(+ many=True,+ help_text=f"Stuck cohorts, oldest last_calculation first (max {MAX_STUCK_COHORTS_LISTED}).",+ )+ total_count = serializers.IntegerField(help_text="Total number of stuck cohorts instance-wide.")+++class StaffCohortRecalculateSerializer(serializers.Serializer):+ cohort_ids = _cohort_ids_field(+ f"Cohort ids to force-recalculate (max {MAX_COHORTS_PER_RECALCULATE} per request).",+ max_length=MAX_COHORTS_PER_RECALCULATE,+ )+++class StaffCohortSkippedSerializer(serializers.Serializer):+ cohort_id = serializers.IntegerField(help_text="Cohort id that was skipped.")+ reason = serializers.CharField(help_text="Why the cohort was not enqueued for recalculation.")+++class StaffCohortFailedSerializer(serializers.Serializer):+ cohort_id = serializers.IntegerField(help_text="Cohort id that raised while being enqueued.")+ error = serializers.CharField(help_text="Error message from the failed enqueue attempt.")+++@extend_schema_serializer(many=False)+class StaffCohortRecalculateResponseSerializer(serializers.Serializer):+ queued_cohort_ids = serializers.ListField(+ child=serializers.IntegerField(),+ help_text="Cohort ids for which a recalculation was enqueued (including their dependency chains).",+ )+ partial_cohort_ids = serializers.ListField(+ child=serializers.IntegerField(),+ help_text="Subset of queued_cohort_ids whose dependency chain failed to resolve, so only the cohort "+ "itself (not its dependents/dependencies) was enqueued. Those related cohorts are still stale; "+ "re-request recalculation for them explicitly once the dependency issue is fixed.",+ )+ failed_cohort_ids = StaffCohortFailedSerializer(+ many=True,+ help_text="Cohort ids that raised while being enqueued and were not queued at all. Cohorts listed "+ "elsewhere in this response already had their enqueue attempted; retry only these ids rather than "+ "the whole batch.",+ )+ skipped = StaffCohortSkippedSerializer(+ many=True, help_text="Cohorts that exist but were not enqueued, with the reason."+ )+ not_found_cohort_ids = serializers.ListField(+ child=serializers.IntegerField(), help_text="Requested cohort ids that do not exist."+ )+++class CohortsStaffToolsViewSet(viewsets.ViewSet):+ """+ Staff-only, unscoped cohort calculation tooling.++ Replaces the prod-shell runbook for stuck cohort calculations: look up any team's cohort by+ id, list cohorts whose calculation is stuck, and force-recalculate by bumping+ pending_version and enqueueing through the same task path organic saves use.++ Registered on the root router so it is not team-nested; staff act on cohorts in teams they+ do not belong to. Cohort.objects is not fail-closed today (the model is on the scoping+ baseline) — if Cohort migrates to a fail-closed manager, these cross-team queries must+ switch to the explicit unscoped escape hatch.+ """++ # 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=StaffCohortLookupQuerySerializer,+ responses={200: OpenApiResponse(response=StaffCohortLookupResponseSerializer)},+ )+ def list(self, request: request.Request, **kwargs: Any) -> response.Response:+ # Dedupe (preserving order) so a caller passing the same id twice doesn't get duplicate+ # rows in `results`.+ cohort_ids: list[int] = list(dict.fromkeys(request.validated_query_data["cohort_ids"]))+ # No deleted=False filter: staff need to see a deleted cohort's state to explain why it+ # stopped calculating.+ # Staff-only, cross-team by design: see class docstring.+ # nosemgrep: idor-lookup-without-team+ cohorts = Cohort.objects.select_related("team").filter(id__in=cohort_ids)+ cohorts_by_id = {cohort.id: cohort for cohort in cohorts}+ found = [cohorts_by_id[cohort_id] for cohort_id in cohort_ids if cohort_id in cohorts_by_id]+ not_found_ids = [cohort_id for cohort_id in cohort_ids if cohort_id not in cohorts_by_id]++ return response.Response(+ StaffCohortLookupResponseSerializer({"results": found, "not_found_cohort_ids": not_found_ids}).data+ )++ @validated_request(responses={200: OpenApiResponse(response=StaffStuckCohortsResponseSerializer)})+ @action(methods=["GET"], detail=False)+ def stuck(self, request: request.Request, **kwargs: Any) -> response.Response:+ # Same definition of "stuck" the periodic reset task uses: is_calculating for over an+ # hour past the last completed calculation, dynamic cohorts only.+ queryset = get_stuck_cohort_calculation_candidates_queryset()+ total_count = queryset.count()+ stuck = queryset.select_related("team").order_by("last_calculation")[:MAX_STUCK_COHORTS_LISTED]++ return response.Response(+ StaffStuckCohortsResponseSerializer({"results": list(stuck), "total_count": total_count}).data+ )++ @validated_request(+ request_serializer=StaffCohortRecalculateSerializer,+ responses={202: OpenApiResponse(response=StaffCohortRecalculateResponseSerializer)},+ )+ @action(methods=["POST"], detail=False)+ def recalculate(self, request: request.Request, **kwargs: Any) -> response.Response:+ cohort_ids: list[int] = list(dict.fromkeys(request.validated_data["cohort_ids"]))+ # Staff-only, cross-team by design: see class docstring.+ # nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get+ cohorts_by_id = {cohort.id: cohort for cohort in Cohort.objects.filter(id__in=cohort_ids)}++ queued_ids: list[int] = []+ partial_ids: list[int] = []+ failed: list[dict[str, Any]] = []+ skipped: list[dict[str, Any]] = []+ not_found_ids: list[int] = []+ for cohort_id in cohort_ids:+ cohort = cohorts_by_id.get(cohort_id)+ if cohort is None:+ not_found_ids.append(cohort_id)+ elif cohort.deleted:+ skipped.append({"cohort_id": cohort_id, "reason": SKIP_REASON_DELETED})+ elif cohort.is_static:+ skipped.append({"cohort_id": cohort_id, "reason": SKIP_REASON_STATIC})+ else:+ # Deliberately no is_calculating guard: stuck cohorts are the whole point, and+ # the pending_version bump supersedes any stale in-flight run.+ # Caught per-cohort so one bad cohort doesn't 500 the whole batch and hide which+ # of the earlier cohorts in the loop already had their version bumped and task+ # enqueued (those must not be retried; only failed_cohort_ids should be).+ try:+ # IsAuthenticated + IsStaffUser guarantee a real User here.+ fully_resolved = increment_version_and_enqueue_calculate_cohort(+ cohort, initiating_user=cast(User, request.user)+ )+ except Exception as e:+ logger.exception("cohorts_staff_recalculate_enqueue_failed", cohort_id=cohort_id, error=str(e))+ capture_exception(e)+ failed.append({"cohort_id": cohort_id, "error": str(e)})+ else:+ queued_ids.append(cohort_id)+ if not fully_resolved:+ partial_ids.append(cohort_id)++ logger.info(+ "cohorts_staff_recalculate",+ staff_user_id=request.user.id,+ was_impersonated=is_impersonated(request),+ queued_cohort_ids=queued_ids,+ partial_cohort_ids=partial_ids,+ failed_cohort_ids=[f["cohort_id"] for f in failed],+ skipped=skipped,+ not_found_cohort_ids=not_found_ids,+ )++ return response.Response(+ {+ "queued_cohort_ids": queued_ids,+ "partial_cohort_ids": partial_ids,+ "failed_cohort_ids": failed,+ "skipped": skipped,+ "not_found_cohort_ids": not_found_ids,+ },+ status=status.HTTP_202_ACCEPTED,+ )diff --git a/products/cohorts/backend/routes.py b/products/cohorts/backend/routes.pynew file mode 100644index 000000000000..b9d5cf558d79--- /dev/null+++ b/products/cohorts/backend/routes.py@@ -0,0 +1,8 @@+from posthog.api.routing import RouterRegistry++from products.cohorts.backend.api import staff_tools+++def register_routes(routers: RouterRegistry) -> None:+ # Staff-only, unscoped cohorts tooling: root-level so it is not team-nested.+ routers.root.register(r"cohorts_staff", staff_tools.CohortsStaffToolsViewSet, "cohorts_staff")diff --git a/products/cohorts/backend/test/test_staff_tools_api.py b/products/cohorts/backend/test/test_staff_tools_api.pynew file mode 100644index 000000000000..ec147a5f952f--- /dev/null+++ b/products/cohorts/backend/test/test_staff_tools_api.py@@ -0,0 +1,187 @@+from datetime import timedelta++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.utils import timezone++from parameterized import parameterized+from rest_framework import status++from posthog.models import Organization, Team++from products.cohorts.backend.models.cohort import Cohort+++class TestCohortsStaffToolsAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.user.is_staff = True+ self.user.save()++ def _create_cross_org_cohort(self, **kwargs) -> Cohort:+ 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())+ return Cohort.objects.create(team=other_team, name="Cross Org Cohort", **kwargs)++ @parameterized.expand(+ [+ ("lookup", "get", "/api/cohorts_staff/?cohort_ids=1"),+ ("stuck", "get", "/api/cohorts_staff/stuck/"),+ ("recalculate", "post", "/api/cohorts_staff/recalculate/"),+ ]+ )+ def test_non_staff_user_gets_403(self, _name, method, url):+ self.user.is_staff = False+ self.user.save()++ response = getattr(self.client, method)(url)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_lookup_returns_cohort_from_organization_staff_user_does_not_belong_to(self):+ # The whole point of this endpoint: staff must reach cohorts in teams they aren't a+ # member of. Guards against someone reintroducing membership scoping on the viewset.+ cohort = self._create_cross_org_cohort(+ is_calculating=True,+ last_calculation=timezone.now() - timedelta(hours=2),+ errors_calculating=3,+ version=4,+ pending_version=5,+ count=123,+ )++ response = self.client.get(f"/api/cohorts_staff/?cohort_ids={cohort.id},999999999")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ data = response.json()+ self.assertEqual(data["not_found_cohort_ids"], [999999999])+ (result,) = data["results"]+ self.assertEqual(result["id"], cohort.id)+ self.assertEqual(result["name"], "Cross Org Cohort")+ self.assertEqual(result["team_id"], cohort.team_id)+ self.assertEqual(result["team_name"], "Cross Org Team")+ self.assertEqual(result["project_id"], cohort.team.project_id)+ self.assertTrue(result["is_calculating"])+ self.assertEqual(result["errors_calculating"], 3)+ self.assertEqual(result["version"], 4)+ self.assertEqual(result["pending_version"], 5)+ self.assertEqual(result["count"], 123)++ def test_lookup_rejects_more_than_max_cohorts(self):+ cohort_ids = ",".join(str(i) for i in range(1, 52))+ response = self.client.get(f"/api/cohorts_staff/?cohort_ids={cohort_ids}")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_lookup_includes_deleted_cohorts(self):+ cohort = Cohort.objects.create(team=self.team, name="Deleted Cohort", deleted=True)++ response = self.client.get(f"/api/cohorts_staff/?cohort_ids={cohort.id}")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ (result,) = response.json()["results"]+ self.assertTrue(result["deleted"])++ def test_stuck_returns_only_stuck_dynamic_cohorts(self):+ two_hours_ago = timezone.now() - timedelta(hours=2)+ stuck = Cohort.objects.create(team=self.team, name="Stuck", is_calculating=True, last_calculation=two_hours_ago)+ Cohort.objects.create(team=self.team, name="Fresh", is_calculating=True, last_calculation=timezone.now())+ Cohort.objects.create(+ team=self.team, name="Static", is_static=True, is_calculating=True, last_calculation=two_hours_ago+ )+ Cohort.objects.create(+ team=self.team,+ name="Deleted",+ deleted=True,+ is_calculating=True,+ last_calculation=two_hours_ago,+ )++ response = self.client.get("/api/cohorts_staff/stuck/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ data = response.json()+ self.assertEqual([result["id"] for result in data["results"]], [stuck.id])+ self.assertEqual(data["total_count"], 1)++ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_recalculate_bumps_version_and_enqueues_with_initiating_user(self, mock_delay):+ cohort = self._create_cross_org_cohort(is_calculating=True, pending_version=7)++ response = self.client.post("/api/cohorts_staff/recalculate/", {"cohort_ids": [cohort.id, 999999999]})+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)++ data = response.json()+ self.assertEqual(data["queued_cohort_ids"], [cohort.id])+ self.assertEqual(data["skipped"], [])+ self.assertEqual(data["not_found_cohort_ids"], [999999999])++ cohort.refresh_from_db()+ self.assertEqual(cohort.pending_version, 8)+ self.assertTrue(cohort.is_calculating)+ mock_delay.assert_called_once_with(cohort.id, 8, self.user.id)++ @parameterized.expand(+ [+ ("static", {"is_static": True}, "Static cohorts"),+ ("deleted", {"deleted": True}, "deleted"),+ ]+ )+ @patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")+ def test_recalculate_skips_with_reason_and_does_not_enqueue(+ self, _name, cohort_kwargs, reason_fragment, mock_delay+ ):+ cohort = Cohort.objects.create(team=self.team, name="Skipped", **cohort_kwargs)++ response = self.client.post("/api/cohorts_staff/recalculate/", {"cohort_ids": [cohort.id]})+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)++ data = response.json()+ self.assertEqual(data["queued_cohort_ids"], [])+ (skipped,) = data["skipped"]+ self.assertEqual(skipped["cohort_id"], cohort.id)+ self.assertIn(reason_fragment, skipped["reason"])+ mock_delay.assert_not_called()++ def test_recalculate_rejects_more_than_max_cohorts(self):+ response = self.client.post("/api/cohorts_staff/recalculate/", {"cohort_ids": list(range(1, 12))})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ @patch("products.cohorts.backend.api.staff_tools.increment_version_and_enqueue_calculate_cohort")+ def test_recalculate_reports_partial_when_dependency_resolution_falls_back(self, mock_increment):+ # increment_version_and_enqueue_calculate_cohort returns False when it fell back to+ # enqueueing just this cohort because resolving its dependency chain failed. The+ # cohort is still queued, but the operator needs to know the dependency chain was skipped.+ mock_increment.return_value = False+ cohort = Cohort.objects.create(team=self.team, name="Cohort", pending_version=1)++ response = self.client.post("/api/cohorts_staff/recalculate/", {"cohort_ids": [cohort.id]})+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)++ data = response.json()+ self.assertEqual(data["queued_cohort_ids"], [cohort.id])+ self.assertEqual(data["partial_cohort_ids"], [cohort.id])++ @patch("products.cohorts.backend.api.staff_tools.increment_version_and_enqueue_calculate_cohort")+ def test_recalculate_continues_batch_and_reports_failure_when_one_cohort_errors(self, mock_increment):+ # A raise for one cohort must not 500 the whole request: earlier cohorts in the batch+ # already had their version bumped and task enqueued, so losing that in a 500 would make+ # a caller retry the full batch and double-enqueue them.+ cohort_ok = Cohort.objects.create(team=self.team, name="Ok", pending_version=1)+ cohort_bad = Cohort.objects.create(team=self.team, name="Bad", pending_version=1)++ def side_effect(cohort, *, initiating_user):+ if cohort.id == cohort_bad.id:+ raise RuntimeError("boom")+ return True++ mock_increment.side_effect = side_effect++ response = self.client.post("/api/cohorts_staff/recalculate/", {"cohort_ids": [cohort_ok.id, cohort_bad.id]})+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)++ data = response.json()+ self.assertEqual(data["queued_cohort_ids"], [cohort_ok.id])+ (failed,) = data["failed_cohort_ids"]+ self.assertEqual(failed["cohort_id"], cohort_bad.id)+ self.assertIn("boom", failed["error"])diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.tsindex cad3d92e573f..f2f96bb5ba6b 100644--- a/products/cohorts/frontend/generated/api.schemas.ts+++ b/products/cohorts/frontend/generated/api.schemas.ts@@ -7,6 +7,115 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+export interface StaffCohortApi {+ /** Cohort id. */+ id: number+ /**+ * Cohort name.+ * @nullable+ */+ name: string | null+ /** Id of the team the cohort belongs to. */+ team_id: number+ /** Name of the team the cohort belongs to. */+ team_name: string+ /** Project id the cohort's team belongs to, for building /project/<id>/cohorts/<id> links. */+ project_id: number+ /** Whether the cohort is soft-deleted. */+ deleted: boolean+ /** Whether the cohort is static (populated once from a source rather than recalculated). */+ is_static: boolean+ /** Whether a calculation is currently marked as in flight. */+ is_calculating: boolean+ /**+ * When the last calculation completed, or null if never calculated.+ * @nullable+ */+ last_calculation: string | null+ /**+ * Duration of the last completed calculation in milliseconds.+ * @nullable+ */+ last_calculation_duration_ms: number | null+ /** Consecutive calculation failures; above 20 the cohort is excluded from periodic recalculation. */+ errors_calculating: number+ /**+ * When the last calculation error was recorded.+ * @nullable+ */+ last_error_at: string | null+ /**+ * Version of the last completed calculation.+ * @nullable+ */+ version: number | null+ /**+ * Version most recently requested; greater than `version` while a calculation is pending or stuck.+ * @nullable+ */+ pending_version: number | null+ /**+ * Number of persons in the cohort as of the last completed calculation.+ * @nullable+ */+ count: number | null+ /**+ * When the cohort was created.+ * @nullable+ */+ created_at: string | null+}++export interface StaffCohortLookupResponseApi {+ /** Requested cohorts, in request order. */+ results: StaffCohortApi[]+ /** Requested cohort ids that do not exist. */+ not_found_cohort_ids: number[]+}++export interface StaffCohortRecalculateApi {+ /**+ * Cohort ids to force-recalculate (max 10 per request).+ * @minItems 1+ * @maxItems 10+ */+ cohort_ids: number[]+}++export interface StaffCohortFailedApi {+ /** Cohort id that raised while being enqueued. */+ cohort_id: number+ /** Error message from the failed enqueue attempt. */+ error: string+}++export interface StaffCohortSkippedApi {+ /** Cohort id that was skipped. */+ cohort_id: number+ /** Why the cohort was not enqueued for recalculation. */+ reason: string+}++export interface StaffCohortRecalculateResponseApi {+ /** Cohort ids for which a recalculation was enqueued (including their dependency chains). */+ queued_cohort_ids: number[]+ /** Subset of queued_cohort_ids whose dependency chain failed to resolve, so only the cohort itself (not its dependents/dependencies) was enqueued. Those related cohorts are still stale; re-request recalculation for them explicitly once the dependency issue is fixed. */+ partial_cohort_ids: number[]+ /** Cohort ids that raised while being enqueued and were not queued at all. Cohorts listed elsewhere in this response already had their enqueue attempted; retry only these ids rather than the whole batch. */+ failed_cohort_ids: StaffCohortFailedApi[]+ /** Cohorts that exist but were not enqueued, with the reason. */+ skipped: StaffCohortSkippedApi[]+ /** Requested cohort ids that do not exist. */+ not_found_cohort_ids: number[]+}++export interface StaffStuckCohortsResponseApi {+ /** Stuck cohorts, oldest last_calculation first (max 100). */+ results: StaffCohortApi[]+ /** Total number of stuck cohorts instance-wide. */+ total_count: number+}+export type PropertyGroupOperatorApi = (typeof PropertyGroupOperatorApi)[keyof typeof PropertyGroupOperatorApi]export const PropertyGroupOperatorApi = {@@ -415,6 +524,15 @@ export interface CohortUsedInResponseApi {cohorts: CohortUsedInCohortsBlockApi}+export type CohortsStaffListParams = {+ /**+ * Cohort ids to look up (max 50 per request). Repeat the param (?cohort_ids=1&cohort_ids=2) or pass one comma-separated value (?cohort_ids=1,2).+ * @minItems 1+ * @maxItems 50+ */+ cohort_ids: number[]+}+export type CohortsListParams = {/*** Return a basic payload that omits the heavy `filters`, `query`, and `groups` fields. Useful for pickers that only need id/name/count.diff --git a/products/cohorts/frontend/generated/api.ts b/products/cohorts/frontend/generated/api.tsindex 5f0a32774d6a..463600471208 100644--- a/products/cohorts/frontend/generated/api.ts+++ b/products/cohorts/frontend/generated/api.ts@@ -14,10 +14,15 @@ import type {CohortUsedInResponseApi,CohortsListParams,CohortsPersonsRetrieveParams,+ CohortsStaffListParams,PaginatedCohortListApi,PatchedAddPersonsToStaticCohortRequestApi,PatchedCohortApi,PatchedRemovePersonRequestApi,+ StaffCohortLookupResponseApi,+ StaffCohortRecalculateApi,+ StaffCohortRecalculateResponseApi,+ StaffStuckCohortsResponseApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -37,6 +42,93 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getCohortsStaffListUrl = (params: CohortsStaffListParams) => {+ 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/cohorts_staff/?${stringifiedParams}` : `/api/cohorts_staff/`+}++/**+ * Staff-only, unscoped cohort calculation tooling.+ *+ * Replaces the prod-shell runbook for stuck cohort calculations: look up any team's cohort by+ * id, list cohorts whose calculation is stuck, and force-recalculate by bumping+ * pending_version and enqueueing through the same task path organic saves use.+ *+ * Registered on the root router so it is not team-nested; staff act on cohorts in teams they+ * do not belong to. Cohort.objects is not fail-closed today (the model is on the scoping+ * baseline) — if Cohort migrates to a fail-closed manager, these cross-team queries must+ * switch to the explicit unscoped escape hatch.+ */+export const cohortsStaffList = async (+ params: CohortsStaffListParams,+ options?: RequestInit+): Promise<StaffCohortLookupResponseApi> => {+ return apiMutator<StaffCohortLookupResponseApi>(getCohortsStaffListUrl(params), {+ ...options,+ method: 'GET',+ })+}++export const getCohortsStaffRecalculateCreateUrl = () => {+ return `/api/cohorts_staff/recalculate/`+}++/**+ * Staff-only, unscoped cohort calculation tooling.+ *+ * Replaces the prod-shell runbook for stuck cohort calculations: look up any team's cohort by+ * id, list cohorts whose calculation is stuck, and force-recalculate by bumping+ * pending_version and enqueueing through the same task path organic saves use.+ *+ * Registered on the root router so it is not team-nested; staff act on cohorts in teams they+ * do not belong to. Cohort.objects is not fail-closed today (the model is on the scoping+ * baseline) — if Cohort migrates to a fail-closed manager, these cross-team queries must+ * switch to the explicit unscoped escape hatch.+ */+export const cohortsStaffRecalculateCreate = async (+ staffCohortRecalculateApi: StaffCohortRecalculateApi,+ options?: RequestInit+): Promise<StaffCohortRecalculateResponseApi> => {+ return apiMutator<StaffCohortRecalculateResponseApi>(getCohortsStaffRecalculateCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(staffCohortRecalculateApi),+ })+}++export const getCohortsStaffStuckRetrieveUrl = () => {+ return `/api/cohorts_staff/stuck/`+}++/**+ * Staff-only, unscoped cohort calculation tooling.+ *+ * Replaces the prod-shell runbook for stuck cohort calculations: look up any team's cohort by+ * id, list cohorts whose calculation is stuck, and force-recalculate by bumping+ * pending_version and enqueueing through the same task path organic saves use.+ *+ * Registered on the root router so it is not team-nested; staff act on cohorts in teams they+ * do not belong to. Cohort.objects is not fail-closed today (the model is on the scoping+ * baseline) — if Cohort migrates to a fail-closed manager, these cross-team queries must+ * switch to the explicit unscoped escape hatch.+ */+export const cohortsStaffStuckRetrieve = async (options?: RequestInit): Promise<StaffStuckCohortsResponseApi> => {+ return apiMutator<StaffStuckCohortsResponseApi>(getCohortsStaffStuckRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}+export const getCohortsListUrl = (projectId: string, params?: CohortsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/cohorts/frontend/generated/api.zod.ts b/products/cohorts/frontend/generated/api.zod.tsindex 655b11ecccd9..c8acd8e4ca8b 100644--- a/products/cohorts/frontend/generated/api.zod.ts+++ b/products/cohorts/frontend/generated/api.zod.ts@@ -9,6 +9,28 @@*/import * as zod from 'zod'+/**+ * Staff-only, unscoped cohort calculation tooling.+ *+ * Replaces the prod-shell runbook for stuck cohort calculations: look up any team's cohort by+ * id, list cohorts whose calculation is stuck, and force-recalculate by bumping+ * pending_version and enqueueing through the same task path organic saves use.+ *+ * Registered on the root router so it is not team-nested; staff act on cohorts in teams they+ * do not belong to. Cohort.objects is not fail-closed today (the model is on the scoping+ * baseline) — if Cohort migrates to a fail-closed manager, these cross-team queries must+ * switch to the explicit unscoped escape hatch.+ */+export const cohortsStaffRecalculateCreateBodyCohortIdsMax = 10++export const CohortsStaffRecalculateCreateBody = /* @__PURE__ */ zod.object({+ cohort_ids: zod+ .array(zod.number())+ .min(1)+ .max(cohortsStaffRecalculateCreateBodyCohortIdsMax)+ .describe('Cohort ids to force-recalculate (max 10 per request).'),+})+export const cohortsCreateBodyNameMax = 400export const cohortsCreateBodyDescriptionMax = 1000diff --git a/products/cohorts/frontend/staff/CohortsStaffToolsScene.tsx b/products/cohorts/frontend/staff/CohortsStaffToolsScene.tsxnew file mode 100644index 000000000000..db902d9f83a5--- /dev/null+++ b/products/cohorts/frontend/staff/CohortsStaffToolsScene.tsx@@ -0,0 +1,128 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonInput } 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 { cohortsStaffToolsLogic, parseCohortIds } from './cohortsStaffToolsLogic'+import { StaffCohortsTable } from './StaffCohortsTable'++export const scene: SceneExport = {+ component: CohortsStaffToolsScene,+ logic: cohortsStaffToolsLogic,+}++function LookupPanel(): JSX.Element {+ const { cohortIdsInput, lookupResponse, lookedUpCohorts, lookupResponseLoading } = useValues(cohortsStaffToolsLogic)+ const { setCohortIdsInput, lookUpCohorts, recalculateCohorts } = useActions(cohortsStaffToolsLogic)++ const hasIds = parseCohortIds(cohortIdsInput).length > 0+ const notFound = lookupResponse?.not_found_cohort_ids ?? []++ return (+ <div className="space-y-2">+ <h3 className="mb-0">Look up cohorts</h3>+ <div className="flex items-center gap-2">+ <LemonInput+ className="flex-1"+ placeholder="Cohort ids, comma-separated (e.g. 128418, 34012)"+ aria-label="Cohort ids to look up"+ value={cohortIdsInput}+ onChange={setCohortIdsInput}+ onPressEnter={() => hasIds && !lookupResponseLoading && lookUpCohorts()}+ data-attr="cohorts-staff-lookup-input"+ />+ <LemonButton+ type="primary"+ size="small"+ onClick={() => lookUpCohorts()}+ loading={lookupResponseLoading}+ disabledReason={!hasIds ? 'Enter at least one cohort id' : undefined}+ >+ Look up+ </LemonButton>+ </div>+ {notFound.length > 0 && (+ <LemonBanner type="warning">Cohort ids not found: {notFound.join(', ')}</LemonBanner>+ )}+ <StaffCohortsTable+ cohorts={lookedUpCohorts}+ loading={lookupResponseLoading}+ emptyState="Enter one or more cohort ids to inspect their calculation state."+ onRecalculate={(cohortId) => recalculateCohorts({ cohortIds: [cohortId] })}+ />+ </div>+ )+}++function StuckCohortsPanel(): JSX.Element {+ const { stuckCohorts, stuckResponse, stuckResponseLoading } = useValues(cohortsStaffToolsLogic)+ const { loadStuckCohorts, recalculateCohorts } = useActions(cohortsStaffToolsLogic)++ const totalCount = stuckResponse?.total_count ?? 0++ return (+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <h3 className="mb-0">Stuck cohorts</h3>+ {totalCount > stuckCohorts.length && (+ <span className="text-secondary">+ showing {stuckCohorts.length} of {totalCount}+ </span>+ )}+ <LemonButton+ type="tertiary"+ size="small"+ className="ml-auto"+ loading={stuckResponseLoading}+ onClick={() => loadStuckCohorts()}+ >+ Refresh+ </LemonButton>+ </div>+ <p className="text-secondary mb-0">+ Dynamic cohorts marked as calculating whose last completed calculation is over an hour old. Their+ calculation task likely died without resetting the flag.+ </p>+ <StaffCohortsTable+ cohorts={stuckCohorts}+ loading={stuckResponseLoading}+ emptyState="No stuck cohorts right now."+ onRecalculate={(cohortId) => recalculateCohorts({ cohortIds: [cohortId] })}+ />+ </div>+ )+}++export function CohortsStaffToolsScene(): 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="Cohorts staff tools"+ description="Look up cohorts across all teams, inspect their calculation state, and force recalculation of stuck cohorts."+ resourceType={{ type: 'cohort' }}+ actions={+ <LemonButton type="secondary" size="small" to={urls.featureFlagsStaffTools()}>+ Flags staff tools+ </LemonButton>+ }+ />+ <div className="space-y-6">+ <LookupPanel />+ <StuckCohortsPanel />+ </div>+ </SceneContent>+ )+}diff --git a/products/cohorts/frontend/staff/StaffCohortsTable.tsx b/products/cohorts/frontend/staff/StaffCohortsTable.tsxnew file mode 100644index 000000000000..c89200f4297b--- /dev/null+++ b/products/cohorts/frontend/staff/StaffCohortsTable.tsx@@ -0,0 +1,164 @@+import { useValues } from 'kea'++import { LemonButton, LemonDialog, LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'++import { cohortsStaffToolsLogic, StaffCohort } from './cohortsStaffToolsLogic'++function recalculateDisabledReason(cohort: StaffCohort): string | undefined {+ if (cohort.deleted) {+ return 'This cohort is deleted'+ }+ if (cohort.is_static) {+ return 'Static cohorts are populated from their source and cannot be recalculated'+ }+ return undefined+}++export function StaffCohortsTable({+ cohorts,+ loading,+ emptyState,+ onRecalculate,+}: {+ cohorts: StaffCohort[]+ loading: boolean+ emptyState: string+ onRecalculate: (cohortId: number) => void+}): JSX.Element {+ const { pendingRecalculateCohortIds, recalculateResultLoading } = useValues(cohortsStaffToolsLogic)++ const columns: LemonTableColumns<StaffCohort> = [+ {+ title: 'Cohort',+ key: 'cohort',+ render: (_, cohort) => (+ <span>+ <Link to={urls.project(cohort.project_id, urls.cohort(cohort.id))}>+ {cohort.name || 'Untitled'}+ </Link>{' '}+ <span className="text-secondary">(#{cohort.id})</span>+ </span>+ ),+ },+ {+ title: 'Team',+ key: 'team',+ render: (_, cohort) => (+ <span>+ {cohort.team_name} <span className="text-secondary">(#{cohort.team_id})</span>+ </span>+ ),+ },+ {+ title: 'State',+ key: 'state',+ render: (_, cohort) => (+ <span className="flex flex-wrap gap-1">+ {cohort.deleted && <LemonTag type="danger">Deleted</LemonTag>}+ {cohort.is_static && <LemonTag type="muted">Static</LemonTag>}+ {cohort.is_calculating && <LemonTag type="completion">Calculating</LemonTag>}+ {!cohort.deleted && !cohort.is_static && !cohort.is_calculating && (+ <LemonTag type="success">Idle</LemonTag>+ )}+ </span>+ ),+ },+ {+ title: 'Version',+ key: 'version',+ tooltip: 'Completed version → requested version. A lasting mismatch means a calculation is stuck.',+ render: (_, cohort) =>+ cohort.pending_version !== null && cohort.pending_version !== cohort.version ? (+ <span className="text-warning font-semibold">+ {cohort.version ?? '–'} → {cohort.pending_version}+ </span>+ ) : (+ <span>{cohort.version ?? '–'}</span>+ ),+ },+ {+ title: 'Last calculation',+ key: 'last_calculation',+ render: (_, cohort) =>+ cohort.last_calculation ? (+ <TZLabel time={cohort.last_calculation} />+ ) : (+ <span className="text-secondary">Never</span>+ ),+ },+ {+ title: 'Errors',+ key: 'errors',+ render: (_, cohort) =>+ cohort.errors_calculating > 0 ? (+ <span className="flex items-baseline gap-1 text-danger">+ {cohort.errors_calculating}+ {cohort.last_error_at && (+ <span className="flex items-baseline gap-1 text-secondary">+ (last <TZLabel time={cohort.last_error_at} />)+ </span>+ )}+ </span>+ ) : (+ <span className="text-secondary">0</span>+ ),+ },+ {+ title: 'Count',+ key: 'count',+ render: (_, cohort) => cohort.count?.toLocaleString() ?? <span className="text-secondary">–</span>,+ },+ {+ key: 'actions',+ width: 0,+ render: (_, cohort) => {+ const pending = pendingRecalculateCohortIds.includes(cohort.id)+ return (+ <LemonButton+ type="secondary"+ size="small"+ loading={pending}+ disabledReason={+ recalculateDisabledReason(cohort) ??+ (recalculateResultLoading && !pending+ ? 'Another recalculation is being enqueued'+ : undefined)+ }+ onClick={() =>+ LemonDialog.open({+ title: `Force recalculation of cohort ${cohort.id}?`,+ description:+ "This bumps the cohort's pending version and enqueues a full recalculation, " ++ 'including any cohorts it depends on or that depend on it. Any stale in-flight ' ++ 'calculation is superseded.',+ primaryButton: {+ children: 'Force recalculate',+ onClick: () => onRecalculate(cohort.id),+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ }+ data-attr="cohorts-staff-recalculate"+ >+ Force recalculate+ </LemonButton>+ )+ },+ },+ ]++ return (+ <LemonTable+ dataSource={cohorts}+ columns={columns}+ loading={loading}+ rowKey={(cohort) => cohort.id}+ emptyState={emptyState}+ />+ )+}diff --git a/products/cohorts/frontend/staff/cohortsStaffToolsLogic.test.ts b/products/cohorts/frontend/staff/cohortsStaffToolsLogic.test.tsnew file mode 100644index 000000000000..1f58613ef5d2--- /dev/null+++ b/products/cohorts/frontend/staff/cohortsStaffToolsLogic.test.ts@@ -0,0 +1,112 @@+import { MOCK_DEFAULT_USER } from 'lib/api.mock'++import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { userLogic } from 'scenes/userLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { cohortsStaffToolsLogic, parseCohortIds } from './cohortsStaffToolsLogic'++describe('cohortsStaffToolsLogic', () => {+ describe('parseCohortIds', () => {+ it.each([+ ['128418, 34012', [128418, 34012]],+ ['128418, 128418, 34012', [128418, 34012]], // dedupes, preserving order+ ['128418 34012\n99', [128418, 34012, 99]], // tolerant of space/newline separators+ ['', []],+ ['no ids here', []],+ ['-123', []], // rejects rather than silently parsing as cohort 123+ ['123.5', []], // rejects rather than silently parsing as cohorts 123 and 5+ ['123, -456, 789', [123, 789]], // malformed tokens are dropped, valid ones still parsed+ ])('parses %s as %s', (input, expected) => {+ expect(parseCohortIds(input)).toEqual(expected)+ })+ })++ describe('deep link seeding', () => {+ let logic: ReturnType<typeof cohortsStaffToolsLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/cohorts_staff/': { results: [], not_found_cohort_ids: [] },+ '/api/cohorts_staff/stuck/': { results: [], total_count: 0 },+ },+ })+ initKeaTests()+ logic = cohortsStaffToolsLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('seeds the input and looks up the cohort from a deep link', async () => {+ router.actions.push('/cohorts/staff?cohort_id=123')+ await expectLogic(logic).toDispatchActions([+ 'seedCohortFromDeepLink',+ 'lookUpCohorts',+ 'lookUpCohortsSuccess',+ ])+ expectLogic(logic).toMatchValues({ cohortIdsInput: '123' })+ })++ it('does not clobber a manual edit when the URL is revisited with the same cohort id', async () => {+ router.actions.push('/cohorts/staff?cohort_id=123')+ await expectLogic(logic).toDispatchActions(['seedCohortFromDeepLink'])++ logic.actions.setCohortIdsInput('456')+ // Simulates urlToAction re-running for the same URL, e.g. browser back/forward.+ router.actions.push('/cohorts/staff?cohort_id=123')++ expectLogic(logic).toMatchValues({ cohortIdsInput: '456' })+ })++ it('re-seeds when a different cohort id is deep-linked while already seeded', async () => {+ router.actions.push('/cohorts/staff?cohort_id=123')+ await expectLogic(logic).toDispatchActions(['seedCohortFromDeepLink'])++ router.actions.push('/cohorts/staff?cohort_id=456')+ await expectLogic(logic).toDispatchActions(['seedCohortFromDeepLink'])++ expectLogic(logic).toMatchValues({ cohortIdsInput: '456' })+ })+ })++ describe('afterMount', () => {+ beforeEach(() => {+ useMocks({+ get: {+ '/api/cohorts_staff/stuck/': { results: [], total_count: 0 },+ },+ })+ initKeaTests()+ userLogic.mount()+ })++ it('loads stuck cohorts for a staff user', async () => {+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_staff: true })++ const logic = cohortsStaffToolsLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadStuckCohorts', 'loadStuckCohortsSuccess'])+ })++ it('does not load stuck cohorts for a non-staff user hitting the URL directly', () => {+ // The scene component itself blocks non-staff users with an AccessDenied page, but this+ // logic mounts regardless (it's the scene's kea logic). Fetching anyway would 403 and+ // surface a misleading error toast on top of AccessDenied.+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_staff: false })++ const logic = cohortsStaffToolsLogic()+ logic.mount()++ expect(logic.values.stuckResponseLoading).toBe(false)+ })+ })+})diff --git a/products/cohorts/frontend/staff/cohortsStaffToolsLogic.ts b/products/cohorts/frontend/staff/cohortsStaffToolsLogic.tsnew file mode 100644index 000000000000..64be6985cb17--- /dev/null+++ b/products/cohorts/frontend/staff/cohortsStaffToolsLogic.ts@@ -0,0 +1,264 @@+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { urlToAction } from 'kea-router'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { userLogic } from 'scenes/userLogic'++import { cohortsStaffList, cohortsStaffRecalculateCreate, cohortsStaffStuckRetrieve } from '../generated/api'+import type {+ StaffCohortApi,+ StaffCohortLookupResponseApi,+ StaffCohortRecalculateResponseApi,+ StaffStuckCohortsResponseApi,+} from '../generated/api.schemas'++export type StaffCohort = StaffCohortApi++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface cohortsStaffToolsLogicValues {+ cohortIdsInput: string+ lastSeededCohortId: number | null+ lookedUpCohorts: StaffCohort[]+ lookupResponse: StaffCohortLookupResponseApi | null+ lookupResponseLoading: boolean+ pendingRecalculateCohortIds: number[]+ recalculateResult: StaffCohortRecalculateResponseApi | null+ recalculateResultLoading: boolean+ stuckCohorts: StaffCohort[]+ stuckResponse: StaffStuckCohortsResponseApi | null+ stuckResponseLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface cohortsStaffToolsLogicActions {+ loadStuckCohorts: (_: void) => void+ loadStuckCohortsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadStuckCohortsSuccess: (+ stuckResponse: StaffStuckCohortsResponseApi,+ payload?: void+ ) => {+ stuckResponse: StaffStuckCohortsResponseApi+ payload?: void+ }+ lookUpCohorts: (_: void) => void+ lookUpCohortsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ lookUpCohortsSuccess: (+ lookupResponse: StaffCohortLookupResponseApi | null,+ payload?: void+ ) => {+ lookupResponse: StaffCohortLookupResponseApi | null+ payload?: void+ }+ recalculateCohorts: ({ cohortIds }: { cohortIds: number[] }) => {+ cohortIds: number[]+ }+ recalculateCohortsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ recalculateCohortsSuccess: (+ recalculateResult: StaffCohortRecalculateResponseApi,+ payload?: {+ cohortIds: number[]+ }+ ) => {+ recalculateResult: StaffCohortRecalculateResponseApi+ payload?: {+ cohortIds: number[]+ }+ }+ seedCohortFromDeepLink: (cohortId: number) => {+ cohortId: number+ }+ setCohortIdsInput: (input: string) => {+ input: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface cohortsStaffToolsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ lookedUpCohorts: (lookupResponse: StaffCohortLookupResponseApi | null) => StaffCohort[]+ stuckCohorts: (stuckResponse: StaffStuckCohortsResponseApi | null) => StaffCohort[]+ }+}++export type cohortsStaffToolsLogicType = MakeLogicType<+ cohortsStaffToolsLogicValues,+ cohortsStaffToolsLogicActions,+ Record<string, any>,+ cohortsStaffToolsLogicMeta+>++export function parseCohortIds(input: string): number[] {+ // Tolerant of comma/space/newline separated ids, deduped preserving order. Each token must be+ // a plain non-negative integer on its own: a digit-run match (e.g. `\d+` over the whole+ // string) would silently turn "-123" into cohort 123 and "123.5" into cohorts 123 and 5.+ const ids = new Set<number>()+ for (const token of input.split(/[\s,]+/)) {+ if (token && /^\d+$/.test(token)) {+ ids.add(Number(token))+ }+ }+ return Array.from(ids)+}++export const cohortsStaffToolsLogic = kea<cohortsStaffToolsLogicType>([+ path(['products', 'cohorts', 'frontend', 'staff', 'cohortsStaffToolsLogic']),+ actions({+ setCohortIdsInput: (input: string) => ({ input }),+ seedCohortFromDeepLink: (cohortId: number) => ({ cohortId }),+ }),+ loaders(({ values }) => ({+ lookupResponse: [+ null as StaffCohortLookupResponseApi | null,+ {+ lookUpCohorts: async (_: void, breakpoint) => {+ const cohortIds = parseCohortIds(values.cohortIdsInput)+ if (cohortIds.length === 0) {+ return null+ }+ const response = await cohortsStaffList({ cohort_ids: cohortIds })+ breakpoint()+ return response+ },+ },+ ],+ stuckResponse: [+ null as StaffStuckCohortsResponseApi | null,+ {+ loadStuckCohorts: async (_: void, breakpoint) => {+ const response = await cohortsStaffStuckRetrieve()+ breakpoint()+ return response+ },+ },+ ],+ recalculateResult: [+ null as StaffCohortRecalculateResponseApi | null,+ {+ recalculateCohorts: async ({ cohortIds }: { cohortIds: number[] }) => {+ return await cohortsStaffRecalculateCreate({ cohort_ids: cohortIds })+ },+ },+ ],+ })),+ reducers({+ cohortIdsInput: [+ '',+ {+ setCohortIdsInput: (_, { input }) => input,+ seedCohortFromDeepLink: (_, { cohortId }) => String(cohortId),+ },+ ],+ // Tracks the last-seeded cohort id so a fresh cohort_id in the URL (e.g. a different+ // support ticket link opened while this scene is already mounted) re-seeds the input,+ // while editing the input after a seed doesn't get clobbered if urlToAction re-runs for+ // the same id (e.g. browser back/forward).+ lastSeededCohortId: [+ null as number | null,+ {+ seedCohortFromDeepLink: (_, { cohortId }) => cohortId,+ },+ ],+ // Reactive per-row in-flight flag for each row's recalculate button.+ pendingRecalculateCohortIds: [+ [] as number[],+ {+ recalculateCohorts: (state, { cohortIds }) => Array.from(new Set([...state, ...cohortIds])),+ recalculateCohortsSuccess: () => [],+ recalculateCohortsFailure: () => [],+ },+ ],+ }),+ selectors({+ lookedUpCohorts: [+ (s) => [s.lookupResponse],+ (lookupResponse: StaffCohortLookupResponseApi | null): StaffCohort[] => lookupResponse?.results ?? [],+ ],+ stuckCohorts: [+ (s) => [s.stuckResponse],+ (stuckResponse: StaffStuckCohortsResponseApi | null): StaffCohort[] => stuckResponse?.results ?? [],+ ],+ }),+ listeners(({ actions, values }) => ({+ seedCohortFromDeepLink: () => {+ actions.lookUpCohorts()+ },+ recalculateCohortsSuccess: ({ recalculateResult }) => {+ const queued = recalculateResult?.queued_cohort_ids ?? []+ const partial = recalculateResult?.partial_cohort_ids ?? []+ const failed = recalculateResult?.failed_cohort_ids ?? []+ const skipped = recalculateResult?.skipped ?? []+ const notFound = recalculateResult?.not_found_cohort_ids ?? []+ if (queued.length > 0) {+ lemonToast.success(+ `Recalculation enqueued for cohort${queued.length === 1 ? '' : 's'} ${queued.join(', ')}. ` ++ 'Refresh in a bit to see progress.'+ )+ }+ if (partial.length > 0) {+ lemonToast.warning(+ `Dependency resolution failed for cohort${partial.length === 1 ? '' : 's'} ${partial.join(+ ', '+ )}; only the cohort itself was enqueued, not its dependents or dependencies. Those may still be stale.`+ )+ }+ for (const { cohort_id, error } of failed) {+ lemonToast.error(`Cohort ${cohort_id} could not be enqueued: ${error}`)+ }+ for (const { cohort_id, reason } of skipped) {+ lemonToast.warning(`Cohort ${cohort_id} was not enqueued: ${reason}`)+ }+ if (notFound.length > 0) {+ lemonToast.warning(`Cohort ids not found: ${notFound.join(', ')}`)+ }+ // Refresh both panels so is_calculating / pending_version reflect the new state.+ if (parseCohortIds(values.cohortIdsInput).length > 0) {+ actions.lookUpCohorts()+ }+ actions.loadStuckCohorts()+ },+ recalculateCohortsFailure: () => {+ lemonToast.error('Failed to enqueue cohort recalculation.')+ },+ lookUpCohortsFailure: () => {+ lemonToast.error('Failed to look up cohorts.')+ },+ loadStuckCohortsFailure: () => {+ lemonToast.error('Failed to load stuck cohorts.')+ },+ })),+ afterMount(({ actions }) => {+ // Scene logic mounts before CohortsStaffToolsScene's is_staff check renders AccessDenied,+ // so a non-staff user hitting this URL directly would otherwise get a 403 toast on top of it.+ if (userLogic.values.user?.is_staff) {+ actions.loadStuckCohorts()+ }+ }),+ urlToAction(({ actions, values }) => ({+ '/cohorts/staff': (_, searchParams) => {+ // Deep link (e.g. from a support ticket): seed the lookup with the cohort id.+ const cohortId = searchParams.cohort_id ? Number(searchParams.cohort_id) : null+ if (cohortId && cohortId !== values.lastSeededCohortId) {+ actions.seedCohortFromDeepLink(cohortId)+ }+ },+ })),+])diff --git a/products/cohorts/manifest.tsx b/products/cohorts/manifest.tsxindex 30bbec58b6dc..d2a4588e9e5a 100644--- a/products/cohorts/manifest.tsx+++ b/products/cohorts/manifest.tsx@@ -6,10 +6,21 @@ import { FileSystemIconColor, ProductManifest } from '../../frontend/src/types'export const manifest: ProductManifest = {name: 'Cohorts',+ scenes: {+ CohortsStaffTools: {+ import: () => import('./frontend/staff/CohortsStaffToolsScene'),+ instanceLevel: true,+ name: 'Cohorts staff tools',+ },+ },+ routes: {+ '/cohorts/staff': ['CohortsStaffTools', 'cohortsStaffTools'],+ },urls: {cohort: (id: string | number): string => `/cohorts/${id}`,cohorts: (): string => '/cohorts',cohortCalculationHistory: (id: string | number): string => `/cohorts/${id}/calculation-history`,+ cohortsStaffTools: (cohortId?: number): string => `/cohorts/staff${cohortId ? `?cohort_id=${cohortId}` : ''}`,},fileSystemTypes: {cohort: {diff --git a/products/cohorts/mcp/tools.yaml b/products/cohorts/mcp/tools.yamlindex f0ab63f7010a..2bce529df522 100644--- a/products/cohorts/mcp/tools.yaml+++ b/products/cohorts/mcp/tools.yaml@@ -231,6 +231,15 @@ tools:Remove a person from a static cohort by their UUID. Only works for static cohorts (is_static: true). Theperson must exist in the project. Idempotent: removing a person who exists but is not a member of the cohortsucceeds silently.+ cohorts-staff-list:+ operation: cohorts_staff_list+ enabled: false+ cohorts-staff-recalculate-create:+ operation: cohorts_staff_recalculate_create+ enabled: false+ cohorts-staff-stuck-retrieve:+ operation: cohorts_staff_stuck_retrieve+ enabled: falsecohorts-update:operation: cohorts_updateenabled: falsediff --git a/products/cohorts/package.json b/products/cohorts/package.jsonindex 6ee702be7f98..9042d8f7e76e 100644--- a/products/cohorts/package.json+++ b/products/cohorts/package.json@@ -9,7 +9,8 @@"kea-router": "catalog:"},"devDependencies": {- "@storybook/react": "catalog:"+ "@storybook/react": "catalog:",+ "kea-test-utils": "catalog:"},"peerDependencies": {"@posthog/icons": "catalog:",diff --git a/products/feature_flags/backend/api/staff_cache.py b/products/feature_flags/backend/api/staff_cache.pyindex 7315da18a5b2..f2499de6d9e4 100644--- a/products/feature_flags/backend/api/staff_cache.py+++ b/products/feature_flags/backend/api/staff_cache.py@@ -16,6 +16,7 @@ from rest_framework.decorators import actionfrom rest_framework.exceptions import NotFound, ValidationErrorfrom rest_framework.permissions import IsAuthenticated+from posthog.api.fields import RepeatedOrCommaSeparatedListFieldfrom posthog.api.mixins import validated_requestfrom posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIASfrom posthog.helpers.impersonation import is_impersonated@@ -62,24 +63,8 @@ WARM_RUN_SCOPES = ["all_teams", "teams_with_flags"]READABLE_CACHE_CHOICES = CACHE_CHOICES-class _RepeatedOrCommaSeparatedListField(serializers.ListField):- """A ListField for query params that accepts values either as repeated keys- (?team_ids=1&team_ids=2) or as a single comma-separated value (?team_ids=1,2). The latter is- how our generated TS client (and plain URLSearchParams) serializes a number[] query param, so- without this a caller using the generated client gets a validation error. Matches the- repeated-or-comma-separated handling already used for query params elsewhere, e.g. the- `include` param in posthog/api/element.py.- """-- def get_value(self, dictionary: Any) -> Any:- value = super().get_value(dictionary)- if isinstance(value, list) and len(value) == 1 and isinstance(value[0], str) and "," in value[0]:- return value[0].split(",")- return value--def _team_ids_field(help_text: str, *, max_length: int = MAX_TEAMS_PER_MUTATION) -> serializers.ListField:- return _RepeatedOrCommaSeparatedListField(+ return RepeatedOrCommaSeparatedListField(child=serializers.IntegerField(), max_length=max_length, help_text=help_text)diff --git a/products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene.tsx b/products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene.tsxindex 3a3dd5933397..979ed652867a 100644--- a/products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene.tsx+++ b/products/feature_flags/frontend/staff/FeatureFlagsStaffToolsScene.tsx@@ -32,9 +32,14 @@ export function FeatureFlagsStaffToolsScene(): JSX.Element {description="Look up any team across all organizations to inspect and rebuild its flag caches, or adjust its feature-flags config."resourceType={{ type: 'feature_flag' }}actions={- <LemonButton type="secondary" size="small" to={urls.instanceSettings()}>- Flags-related instance settings- </LemonButton>+ <>+ <LemonButton type="secondary" size="small" to={urls.cohortsStaffTools()}>+ Cohorts staff tools+ </LemonButton>+ <LemonButton type="secondary" size="small" to={urls.instanceSettings()}>+ Flags-related instance settings+ </LemonButton>+ </>}/><StaffCacheToolsTab />diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 95cf1bb3e15f..db971ddc5b16 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -60401,6 +60401,115 @@ export namespace Schemas {results: StaffCacheTeamStatus[];}+ export interface StaffCohort {+ /** Cohort id. */+ id: number;+ /**+ * Cohort name.+ * @nullable+ */+ name: string | null;+ /** Id of the team the cohort belongs to. */+ team_id: number;+ /** Name of the team the cohort belongs to. */+ team_name: string;+ /** Project id the cohort's team belongs to, for building /project/<id>/cohorts/<id> links. */+ project_id: number;+ /** Whether the cohort is soft-deleted. */+ deleted: boolean;+ /** Whether the cohort is static (populated once from a source rather than recalculated). */+ is_static: boolean;+ /** Whether a calculation is currently marked as in flight. */+ is_calculating: boolean;+ /**+ * When the last calculation completed, or null if never calculated.+ * @nullable+ */+ last_calculation: string | null;+ /**+ * Duration of the last completed calculation in milliseconds.+ * @nullable+ */+ last_calculation_duration_ms: number | null;+ /** Consecutive calculation failures; above 20 the cohort is excluded from periodic recalculation. */+ errors_calculating: number;+ /**+ * When the last calculation error was recorded.+ * @nullable+ */+ last_error_at: string | null;+ /**+ * Version of the last completed calculation.+ * @nullable+ */+ version: number | null;+ /**+ * Version most recently requested; greater than `version` while a calculation is pending or stuck.+ * @nullable+ */+ pending_version: number | null;+ /**+ * Number of persons in the cohort as of the last completed calculation.+ * @nullable+ */+ count: number | null;+ /**+ * When the cohort was created.+ * @nullable+ */+ created_at: string | null;+ }++ export interface StaffCohortFailed {+ /** Cohort id that raised while being enqueued. */+ cohort_id: number;+ /** Error message from the failed enqueue attempt. */+ error: string;+ }++ export interface StaffCohortLookupResponse {+ /** Requested cohorts, in request order. */+ results: StaffCohort[];+ /** Requested cohort ids that do not exist. */+ not_found_cohort_ids: number[];+ }++ export interface StaffCohortRecalculate {+ /**+ * Cohort ids to force-recalculate (max 10 per request).+ * @minItems 1+ * @maxItems 10+ */+ cohort_ids: number[];+ }++ export interface StaffCohortSkipped {+ /** Cohort id that was skipped. */+ cohort_id: number;+ /** Why the cohort was not enqueued for recalculation. */+ reason: string;+ }++ export interface StaffCohortRecalculateResponse {+ /** Cohort ids for which a recalculation was enqueued (including their dependency chains). */+ queued_cohort_ids: number[];+ /** Subset of queued_cohort_ids whose dependency chain failed to resolve, so only the cohort itself (not its dependents/dependencies) was enqueued. Those related cohorts are still stale; re-request recalculation for them explicitly once the dependency issue is fixed. */+ partial_cohort_ids: number[];+ /** Cohort ids that raised while being enqueued and were not queued at all. Cohorts listed elsewhere in this response already had their enqueue attempted; retry only these ids rather than the whole batch. */+ failed_cohort_ids: StaffCohortFailed[];+ /** Cohorts that exist but were not enqueued, with the reason. */+ skipped: StaffCohortSkipped[];+ /** Requested cohort ids that do not exist. */+ not_found_cohort_ids: number[];+ }++ export interface StaffStuckCohortsResponse {+ /** Stuck cohorts, oldest last_calculation first (max 100). */+ results: StaffCohort[];+ /** Total number of stuck cohorts instance-wide. */+ total_count: number;+ }+export interface StaffTeamConfig {/** Team id. */team_id: number;@@ -65785,6 +65894,15 @@ export namespace Schemas {query: _TracingTreeQueryBody;}+ export type CohortsStaffListParams = {+ /**+ * Cohort ids to look up (max 50 per request). Repeat the param (?cohort_ids=1&cohort_ids=2) or pass one comma-separated value (?cohort_ids=1,2).+ * @minItems 1+ * @maxItems 50+ */+ cohort_ids: number[];+ };+export type CustomerAnalyticsExternalAccountsRetrieveParams = {/*** When true, return only accounts with at least one active relationship assignment to a current member of the project's organization.