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): publish warm-all run status from rust warmer to staff ui (#69545)

Phil Haack5a17495db2c5
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index c2c7d169ece9..ada8c09fca69 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -579,6 +579,9 @@ SPECTACULAR_SETTINGS = {
# The metrics query's OTel metric-type filter; without a pinned name it
# collides with the experiments MetricTypeEnum (funnel/ratio/...).
"OtelMetricTypeEnum": ["gauge", "sum", "histogram", "exponential_histogram", "summary"],
+ # Staff flags-cache warm-run status; 'state'/'scope' are collision-prone field names.
+ "FlagsWarmRunStateEnum": ["running", "completed", "cancelled"],
+ "FlagsWarmRunScopeEnum": ["all_teams", "teams_with_flags"],
# bulk_update_tags exposes an identical add/remove/set `action` ChoiceField on both
# BulkUpdateTagsRequest and its UUID subclass, so the shared enum can't be component-prefixed
# unambiguously and auto-resolves to a hash name. Pin it to a stable name.
diff --git a/products/feature_flags/backend/api/staff_cache.py b/products/feature_flags/backend/api/staff_cache.py
index ec00c550c529..7315da18a5b2 100644
--- a/products/feature_flags/backend/api/staff_cache.py
+++ b/products/feature_flags/backend/api/staff_cache.py
@@ -1,15 +1,23 @@
+import json
+import time
from collections.abc import Callable
-from typing import Any
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+from django.conf import settings
+from django.core.cache import caches
+from django.core.cache.backends.base import BaseCache
import structlog
from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiResponse, extend_schema_field, extend_schema_serializer
+from drf_spectacular.utils import OpenApiResponse, extend_schema, 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.exceptions import NotFound, ValidationError
from rest_framework.permissions import IsAuthenticated
from posthog.api.mixins import validated_request
+from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
from posthog.helpers.impersonation import is_impersonated
from posthog.models.team import Team
from posthog.permissions import IsStaffUser
@@ -39,6 +47,17 @@ _READABLE_HYPERCACHES = {
DEFINITIONS: flag_definitions_hypercache,
}
+# Warm-all run status, published to the flags Redis by the Rust warmer
+# (rust/feature-flags/src/flags/warm_run_status.rs). Keys, field names, states,
+# and the staleness threshold are a contract with that module — change in lockstep.
+WARM_RUN_STATUS_CACHE_KEY = "feature_flags/warm_run/status"
+WARM_RUN_CANCEL_CACHE_KEY = "feature_flags/warm_run/cancel"
+WARM_RUN_HEARTBEAT_STALE_SECONDS = 120
+WARM_RUN_CANCEL_TTL_SECONDS = 3600
+
+WARM_RUN_STATES = ["running", "completed", "cancelled"]
+WARM_RUN_SCOPES = ["all_teams", "teams_with_flags"]
+
# Reading and mutating currently share the same choice set.
READABLE_CACHE_CHOICES = CACHE_CHOICES
@@ -148,6 +167,115 @@ class StaffCacheEntryResponseSerializer(serializers.Serializer):
)
+class StaffWarmRunSerializer(serializers.Serializer):
+ run_id = serializers.CharField(help_text="Unique id of the warm-all run.")
+ state = serializers.ChoiceField(
+ choices=WARM_RUN_STATES,
+ help_text=(
+ "'running' while the warmer is working, 'completed' when it finished (per-team failures "
+ "are counted, not fatal), or 'cancelled' when a cancel request was honored."
+ ),
+ )
+ scope = serializers.ChoiceField(
+ choices=WARM_RUN_SCOPES,
+ help_text="Which teams the run covers: every team, or only teams that have ever had a flag.",
+ )
+ total = serializers.IntegerField(help_text="Number of teams the run will warm.")
+ processed = serializers.IntegerField(help_text="Teams processed so far (successful + failed).")
+ successful = serializers.IntegerField(help_text="Teams whose evaluation cache was rebuilt successfully.")
+ failed = serializers.IntegerField(help_text="Teams whose rebuild failed; details are in the warmer's logs.")
+ last_team_id = serializers.IntegerField(
+ allow_null=True,
+ help_text="Highest team id dispatched so far — a resume cursor for operators re-running the warmer.",
+ )
+ started_at = serializers.DateTimeField(help_text="When the run started.")
+ updated_at = serializers.DateTimeField(help_text="Heartbeat: last time the warmer reported progress.")
+ is_stale = serializers.BooleanField(
+ help_text=(
+ "True when the run claims to be running but its heartbeat stopped — the warmer process "
+ "likely died without writing a final state."
+ )
+ )
+ cancel_requested = serializers.BooleanField(
+ help_text="True when a cancel has been requested for this run but the warmer has not yet honored it."
+ )
+
+
+@extend_schema_serializer(many=False)
+class StaffWarmRunResponseSerializer(serializers.Serializer):
+ run = StaffWarmRunSerializer(
+ allow_null=True,
+ help_text="Most recent warm-all run, or null when none has been recorded (or the dedicated flags cache is not configured).",
+ )
+
+
+class StaffWarmRunCancelResponseSerializer(serializers.Serializer):
+ run_id = serializers.CharField(help_text="Id of the run the cancel request targets.")
+ cancel_requested = serializers.BooleanField(help_text="Always true on success.")
+
+
+def _flags_dedicated_cache() -> Optional[BaseCache]:
+ """The dedicated flags Redis as a Django cache, or None when not configured.
+
+ Its config (pickle serializer + zstd compressor + 'posthog' key prefix) mirrors the Rust
+ warmer's Redis client defaults, so both sides read each other's values transparently.
+ """
+ if FLAGS_DEDICATED_CACHE_ALIAS not in settings.CACHES:
+ return None
+ return caches[FLAGS_DEDICATED_CACHE_ALIAS]
+
+
+def _parse_warm_run_status(raw: Optional[str]) -> Optional[dict[str, Any]]:
+ """Parse the warmer's raw status blob, or None when absent/unreadable.
+
+ Tolerant of malformed blobs (e.g. written by a newer binary): any parse failure reads as
+ "no run" rather than a 500 on the staff page.
+ """
+ if raw is None:
+ return None
+ try:
+ run = json.loads(raw)
+ except (TypeError, ValueError):
+ logger.warning("flags_staff_warm_run_status_unparseable")
+ return None
+ if (
+ not isinstance(run, dict)
+ or not isinstance(run.get("run_id"), str)
+ or run.get("state") not in WARM_RUN_STATES
+ or run.get("scope") not in WARM_RUN_SCOPES
+ ):
+ logger.warning("flags_staff_warm_run_status_malformed")
+ return None
+ return run
+
+
+def _as_epoch(value: Any) -> int:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _present_warm_run(run: dict[str, Any], cancel_run_id: Optional[str]) -> dict[str, Any]:
+ """Convert the wire blob (epoch-second timestamps) into the API shape."""
+ updated_at = _as_epoch(run.get("updated_at"))
+ is_stale = run["state"] == "running" and time.time() - updated_at > WARM_RUN_HEARTBEAT_STALE_SECONDS
+ return {
+ "run_id": run["run_id"],
+ "state": run["state"],
+ "scope": run.get("scope"),
+ "total": run.get("total", 0),
+ "processed": run.get("processed", 0),
+ "successful": run.get("successful", 0),
+ "failed": run.get("failed", 0),
+ "last_team_id": run.get("last_team_id"),
+ "started_at": datetime.fromtimestamp(_as_epoch(run.get("started_at")), tz=UTC).isoformat(),
+ "updated_at": datetime.fromtimestamp(updated_at, tz=UTC).isoformat(),
+ "is_stale": is_stale,
+ "cancel_requested": cancel_run_id == run["run_id"],
+ }
+
+
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}.
@@ -294,6 +422,62 @@ class FeatureFlagsStaffCacheViewSet(viewsets.ViewSet):
return response.Response({"team_id": team_id, "cache": cache_kind, "source": source, "data": data})
+ @extend_schema(responses={200: OpenApiResponse(response=StaffWarmRunResponseSerializer)})
+ @action(methods=["GET"], detail=False)
+ def warm_run(self, request: request.Request, **kwargs) -> response.Response:
+ """Status of the most recent warm-all run, published by the Rust warmer."""
+ cache = _flags_dedicated_cache()
+ if cache is None:
+ return response.Response({"run": None})
+
+ # One MGET for both keys, since this endpoint is polled every 5-30s per open staff page.
+ values = cache.get_many([WARM_RUN_STATUS_CACHE_KEY, WARM_RUN_CANCEL_CACHE_KEY])
+ run = _parse_warm_run_status(values.get(WARM_RUN_STATUS_CACHE_KEY))
+ if run is None:
+ return response.Response({"run": None})
+
+ try:
+ presented = _present_warm_run(run, values.get(WARM_RUN_CANCEL_CACHE_KEY))
+ except (OverflowError, OSError, ValueError) as e:
+ logger.warning("flags_staff_warm_run_status_present_failed", error=str(e))
+ return response.Response({"run": None})
+
+ return response.Response({"run": presented})
+
+ @extend_schema(
+ request=None,
+ responses={202: OpenApiResponse(response=StaffWarmRunCancelResponseSerializer)},
+ )
+ @action(methods=["POST"], detail=False, url_path="warm_run/cancel")
+ def cancel_warm_run(self, request: request.Request, **kwargs) -> response.Response:
+ """Request cancellation of the active warm-all run.
+
+ Sets the cancel key the warmer polls between status heartbeats; the run winds down after
+ in-flight teams finish. Cancelling a stale run is allowed (the key is scoped to the run id,
+ so a dead process simply never reads it).
+ """
+ cache = _flags_dedicated_cache()
+ if cache is None:
+ raise ValidationError("The dedicated flags cache (FLAGS_REDIS_URL) is not configured.")
+
+ run = _parse_warm_run_status(cache.get(WARM_RUN_STATUS_CACHE_KEY))
+ if run is None or run["state"] != "running":
+ raise ValidationError("No warm-all run is currently running.")
+
+ cache.set(WARM_RUN_CANCEL_CACHE_KEY, run["run_id"], WARM_RUN_CANCEL_TTL_SECONDS)
+
+ logger.info(
+ "flags_staff_cache_warm_run_cancel",
+ staff_user_id=request.user.id,
+ was_impersonated=is_impersonated(request),
+ run_id=run["run_id"],
+ )
+
+ return response.Response(
+ {"run_id": run["run_id"], "cancel_requested": True},
+ status=status.HTTP_202_ACCEPTED,
+ )
+
@validated_request(
request_serializer=StaffCacheMutationSerializer,
responses={202: OpenApiResponse(response=StaffCacheMutationResponseSerializer)},
diff --git a/products/feature_flags/backend/test/test_staff_cache_api.py b/products/feature_flags/backend/test/test_staff_cache_api.py
index 39f99b48ed42..8e89f9cedc97 100644
--- a/products/feature_flags/backend/test/test_staff_cache_api.py
+++ b/products/feature_flags/backend/test/test_staff_cache_api.py
@@ -1,15 +1,24 @@
+import json
+import time
+
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.conf import settings
+from django.core.cache import caches
from django.http import QueryDict
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from rest_framework import status
+from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
+
from products.feature_flags.backend.api.staff_cache import (
MAX_TEAMS_PER_MUTATION,
READABLE_CACHE_CHOICES,
+ WARM_RUN_CANCEL_CACHE_KEY,
+ WARM_RUN_STATUS_CACHE_KEY,
StaffCacheStatusQuerySerializer,
)
from products.feature_flags.backend.flags_cache import flags_hypercache
@@ -19,6 +28,8 @@ 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/"
+WARM_RUN_URL = "/api/feature_flags_staff_cache/warm_run/"
+WARM_RUN_CANCEL_URL = "/api/feature_flags_staff_cache/warm_run/cancel/"
def _called_once_with(mock, team_id):
@@ -61,6 +72,12 @@ class TestFeatureFlagsStaffCacheAPI(APIBaseTest):
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)
+ warm_run_response = self.client.get(WARM_RUN_URL)
+ self.assertEqual(warm_run_response.status_code, status.HTTP_403_FORBIDDEN)
+
+ cancel_response = self.client.post(WARM_RUN_CANCEL_URL)
+ self.assertEqual(cancel_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
@@ -204,3 +221,136 @@ class TestTeamIdsFieldQueryParamFormats(SimpleTestCase):
serializer = StaffCacheStatusQuerySerializer(data=QueryDict(query_string))
self.assertTrue(serializer.is_valid(), serializer.errors)
self.assertEqual(serializer.validated_data["team_ids"], [1, 2])
+
+
+def _warm_run_blob(**overrides):
+ blob = {
+ "run_id": "run-1",
+ "state": "running",
+ "scope": "teams_with_flags",
+ "total": 100,
+ "processed": 40,
+ "successful": 39,
+ "failed": 1,
+ "last_team_id": 4321,
+ "started_at": int(time.time()) - 60,
+ "updated_at": int(time.time()),
+ }
+ blob.update(overrides)
+ return json.dumps(blob)
+
+
+# Blobs the reader must tolerate (treat as "no run") rather than 500 the staff page:
+# a newer/older warmer binary could write a shape this code doesn't know.
+MALFORMED_STATUS_BLOBS = [
+ ("not_json", "{nope"),
+ ("not_a_dict", json.dumps([1, 2])),
+ ("missing_run_id", json.dumps({"state": "running"})),
+ ("unknown_state", json.dumps({"run_id": "x", "state": "exploded"})),
+]
+
+_CACHES_WITH_FLAGS_DEDICATED = {
+ **settings.CACHES,
+ FLAGS_DEDICATED_CACHE_ALIAS: {
+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
+ "LOCATION": "flags-dedicated-staff-warm-run-tests",
+ },
+}
+
+
+@override_settings(CACHES=_CACHES_WITH_FLAGS_DEDICATED)
+class TestFeatureFlagsStaffWarmRunAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user.is_staff = True
+ self.user.save()
+ self.cache = caches[FLAGS_DEDICATED_CACHE_ALIAS]
+ self.cache.clear()
+
+ def test_returns_null_run_when_no_status_recorded(self):
+ response = self.client.get(WARM_RUN_URL)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIsNone(response.json()["run"])
+
+ def test_handles_missing_dedicated_cache_config(self):
+ # Self-hosted instances without FLAGS_REDIS_URL have no flags_dedicated cache alias;
+ # the endpoints must degrade instead of KeyError-ing into a 500.
+ caches_without = {k: v for k, v in settings.CACHES.items() if k != FLAGS_DEDICATED_CACHE_ALIAS}
+ with override_settings(CACHES=caches_without):
+ get_response = self.client.get(WARM_RUN_URL)
+ self.assertEqual(get_response.status_code, status.HTTP_200_OK)
+ self.assertIsNone(get_response.json()["run"])
+
+ cancel_response = self.client.post(WARM_RUN_CANCEL_URL)
+ self.assertEqual(cancel_response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_reports_fresh_running_run(self):
+ self.cache.set(WARM_RUN_STATUS_CACHE_KEY, _warm_run_blob())
+
+ run = self.client.get(WARM_RUN_URL).json()["run"]
+ self.assertEqual(run["run_id"], "run-1")
+ self.assertEqual(run["state"], "running")
+ self.assertEqual(run["scope"], "teams_with_flags")
+ self.assertEqual(run["total"], 100)
+ self.assertEqual(run["processed"], 40)
+ self.assertEqual(run["successful"], 39)
+ self.assertEqual(run["failed"], 1)
+ self.assertEqual(run["last_team_id"], 4321)
+ self.assertFalse(run["is_stale"])
+ self.assertFalse(run["cancel_requested"])
+
+ def test_running_run_with_dead_heartbeat_is_stale(self):
+ self.cache.set(WARM_RUN_STATUS_CACHE_KEY, _warm_run_blob(updated_at=int(time.time()) - 600))
+ run = self.client.get(WARM_RUN_URL).json()["run"]
+ self.assertTrue(run["is_stale"])
+
+ def test_terminal_run_with_old_heartbeat_is_not_stale(self):
+ self.cache.set(
+ WARM_RUN_STATUS_CACHE_KEY,
+ _warm_run_blob(state="completed", updated_at=int(time.time()) - 600),
+ )
+ run = self.client.get(WARM_RUN_URL).json()["run"]
+ self.assertFalse(run["is_stale"])
+
+ def test_cancel_requested_reflects_only_a_matching_cancel_key(self):
+ self.cache.set(WARM_RUN_STATUS_CACHE_KEY, _warm_run_blob())
+
+ self.cache.set(WARM_RUN_CANCEL_CACHE_KEY, "some-older-run")
+ run = self.client.get(WARM_RUN_URL).json()["run"]
+ self.assertFalse(run["cancel_requested"])
+
+ self.cache.set(WARM_RUN_CANCEL_CACHE_KEY, "run-1")
+ run = self.client.get(WARM_RUN_URL).json()["run"]
+ self.assertTrue(run["cancel_requested"])
+
+ def test_cancel_writes_run_scoped_cancel_key(self):
+ # The warmer only honors a cancel key whose value equals its own run id, so the
+ # endpoint must write exactly the running run's id.
+ self.cache.set(WARM_RUN_STATUS_CACHE_KEY, _warm_run_blob())
+
+ response = self.client.post(WARM_RUN_CANCEL_URL)
+ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
+ self.assertEqual(response.json(), {"run_id": "run-1", "cancel_requested": True})
+ self.assertEqual(self.cache.get(WARM_RUN_CANCEL_CACHE_KEY), "run-1")
+
+ @parameterized.expand(
+ [
+ ("no_run_recorded", None),
+ ("terminal_run", "completed"),
+ ]
+ )
+ def test_cancel_rejected_when_nothing_is_running(self, _name, state):
+ if state is not None:
+ self.cache.set(WARM_RUN_STATUS_CACHE_KEY, _warm_run_blob(state=state))
+
+ response = self.client.post(WARM_RUN_CANCEL_URL)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIsNone(self.cache.get(WARM_RUN_CANCEL_CACHE_KEY))
+
+ @parameterized.expand(MALFORMED_STATUS_BLOBS)
+ def test_malformed_status_blob_reads_as_no_run(self, _name, raw):
+ self.cache.set(WARM_RUN_STATUS_CACHE_KEY, raw)
+
+ response = self.client.get(WARM_RUN_URL)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIsNone(response.json()["run"])
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 82a469d5cc7b..f824bf5a40df 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -99,6 +99,79 @@ export interface StaffCacheEntryResponseApi {
data: StaffCacheEntryResponseApiData
}
+/**
+ * * `running` - running
+ * * `completed` - completed
+ * * `cancelled` - cancelled
+ */
+export type FlagsWarmRunStateEnumApi = (typeof FlagsWarmRunStateEnumApi)[keyof typeof FlagsWarmRunStateEnumApi]
+
+export const FlagsWarmRunStateEnumApi = {
+ Running: 'running',
+ Completed: 'completed',
+ Cancelled: 'cancelled',
+} as const
+
+/**
+ * * `all_teams` - all_teams
+ * * `teams_with_flags` - teams_with_flags
+ */
+export type FlagsWarmRunScopeEnumApi = (typeof FlagsWarmRunScopeEnumApi)[keyof typeof FlagsWarmRunScopeEnumApi]
+
+export const FlagsWarmRunScopeEnumApi = {
+ AllTeams: 'all_teams',
+ TeamsWithFlags: 'teams_with_flags',
+} as const
+
+export interface StaffWarmRunApi {
+ /** Unique id of the warm-all run. */
+ run_id: string
+ /** 'running' while the warmer is working, 'completed' when it finished (per-team failures are counted, not fatal), or 'cancelled' when a cancel request was honored.
+ *
+ * * `running` - running
+ * * `completed` - completed
+ * * `cancelled` - cancelled */
+ state: FlagsWarmRunStateEnumApi
+ /** Which teams the run covers: every team, or only teams that have ever had a flag.
+ *
+ * * `all_teams` - all_teams
+ * * `teams_with_flags` - teams_with_flags */
+ scope: FlagsWarmRunScopeEnumApi
+ /** Number of teams the run will warm. */
+ total: number
+ /** Teams processed so far (successful + failed). */
+ processed: number
+ /** Teams whose evaluation cache was rebuilt successfully. */
+ successful: number
+ /** Teams whose rebuild failed; details are in the warmer's logs. */
+ failed: number
+ /**
+ * Highest team id dispatched so far — a resume cursor for operators re-running the warmer.
+ * @nullable
+ */
+ last_team_id: number | null
+ /** When the run started. */
+ started_at: string
+ /** Heartbeat: last time the warmer reported progress. */
+ updated_at: string
+ /** True when the run claims to be running but its heartbeat stopped — the warmer process likely died without writing a final state. */
+ is_stale: boolean
+ /** True when a cancel has been requested for this run but the warmer has not yet honored it. */
+ cancel_requested: boolean
+}
+
+export interface StaffWarmRunResponseApi {
+ /** Most recent warm-all run, or null when none has been recorded (or the dedicated flags cache is not configured). */
+ run: StaffWarmRunApi | null
+}
+
+export interface StaffWarmRunCancelResponseApi {
+ /** Id of the run the cancel request targets. */
+ run_id: string
+ /** Always true on success. */
+ cancel_requested: boolean
+}
+
export interface StaffTeamConfigApi {
/** Team id. */
team_id: number
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index e66977b7f58d..bd24bb882ddc 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -57,6 +57,8 @@ import type {
StaffTeamConfigListResponseApi,
StaffTeamConfigMutationApi,
StaffTeamSearchResponseApi,
+ StaffWarmRunCancelResponseApi,
+ StaffWarmRunResponseApi,
UserBlastRadiusRequestApi,
UserBlastRadiusResponseApi,
} from './api.schemas'
@@ -202,6 +204,42 @@ export const featureFlagsStaffCacheRebuildCreate = async (
})
}
+export const getFeatureFlagsStaffCacheWarmRunRetrieveUrl = () => {
+ return `/api/feature_flags_staff_cache/warm_run/`
+}
+
+/**
+ * Status of the most recent warm-all run, published by the Rust warmer.
+ */
+export const featureFlagsStaffCacheWarmRunRetrieve = async (
+ options?: RequestInit
+): Promise<StaffWarmRunResponseApi> => {
+ return apiMutator<StaffWarmRunResponseApi>(getFeatureFlagsStaffCacheWarmRunRetrieveUrl(), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getFeatureFlagsStaffCacheWarmRunCancelCreateUrl = () => {
+ return `/api/feature_flags_staff_cache/warm_run/cancel/`
+}
+
+/**
+ * Request cancellation of the active warm-all run.
+ *
+ * Sets the cancel key the warmer polls between status heartbeats; the run winds down after
+ * in-flight teams finish. Cancelling a stale run is allowed (the key is scoped to the run id,
+ * so a dead process simply never reads it).
+ */
+export const featureFlagsStaffCacheWarmRunCancelCreate = async (
+ options?: RequestInit
+): Promise<StaffWarmRunCancelResponseApi> => {
+ return apiMutator<StaffWarmRunCancelResponseApi>(getFeatureFlagsStaffCacheWarmRunCancelCreateUrl(), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getFeatureFlagsStaffTeamConfigListUrl = (params: FeatureFlagsStaffTeamConfigListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
index 8721215f14b0..d51da42fc3a6 100644
--- a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
+++ b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
@@ -1,9 +1,19 @@
-import { useActions, useValues } from 'kea'
+import { useActions, useAsyncActions, useValues } from 'kea'
import { IconEye } from '@posthog/icons'
-import { LemonButton, LemonDialog, LemonSwitch, LemonTable, LemonTableColumns, LemonTag } from '@posthog/lemon-ui'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonDialog,
+ LemonSwitch,
+ LemonTable,
+ LemonTableColumns,
+ LemonTag,
+} from '@posthog/lemon-ui'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
import { truncate } from 'lib/utils/strings'
import {
@@ -13,6 +23,7 @@ import {
StaffCacheKind,
StaffReadableCacheKind,
StaffTeamResult,
+ StaffWarmRun,
} from './featureFlagsStaffToolsLogic'
import { StaffCacheEntryModal } from './StaffCacheEntryModal'
import { StaffTeamSearchInput } from './StaffTeamSearchInput'
@@ -23,6 +34,99 @@ const ALL_CACHES: StaffCacheKind[] = ['evaluation', 'definitions']
const READABLE_CACHE_KINDS: StaffReadableCacheKind[] = ['evaluation', 'definitions']
+const WARM_RUN_STATE_TAGS: Record<StaffWarmRun['state'], { type: 'completion' | 'success' | 'muted'; label: string }> =
+ {
+ running: { type: 'completion', label: 'Running' },
+ completed: { type: 'success', label: 'Completed' },
+ cancelled: { type: 'muted', label: 'Cancelled' },
+ }
+
+const WARM_RUN_SCOPE_LABELS: Record<StaffWarmRun['scope'], string> = {
+ all_teams: 'all teams',
+ teams_with_flags: 'teams with flags',
+}
+
+function WarmRunPanel(): JSX.Element {
+ const { warmRun, warmRunCancelResultLoading } = useValues(featureFlagsStaffToolsLogic)
+ const { cancelWarmRun } = useAsyncActions(featureFlagsStaffToolsLogic)
+
+ if (!warmRun) {
+ return (
+ <div className="border rounded p-4">
+ <h3 className="mb-1">Warm-all run</h3>
+ <p className="text-secondary mb-0">
+ No warm-all run has been recorded. Runs started with the Rust warmer (<code>warm-flags-cache</code>)
+ publish live status here.
+ </p>
+ </div>
+ )
+ }
+
+ const stateTag = WARM_RUN_STATE_TAGS[warmRun.state]
+ const percent = warmRun.total > 0 ? Math.min(100, Math.round((warmRun.processed / warmRun.total) * 100)) : 0
+ const cancelDisabledReason = warmRun.cancel_requested ? 'Cancellation already requested' : undefined
+
+ return (
+ <div className="border rounded p-4 space-y-2">
+ <div className="flex items-center gap-2">
+ <h3 className="mb-0">Warm-all run</h3>
+ <LemonTag type={stateTag.type}>{stateTag.label}</LemonTag>
+ {warmRun.is_stale && <LemonTag type="warning">Stale</LemonTag>}
+ <span className="flex items-baseline gap-1 text-secondary">
+ {WARM_RUN_SCOPE_LABELS[warmRun.scope] ?? warmRun.scope} · started
+ <TZLabel time={warmRun.started_at} />
+ </span>
+ {warmRun.state === 'running' && !warmRun.is_stale && (
+ <LemonButton
+ status="danger"
+ type="secondary"
+ size="small"
+ className="ml-auto"
+ loading={warmRunCancelResultLoading}
+ disabledReason={cancelDisabledReason}
+ onClick={() =>
+ LemonDialog.open({
+ title: 'Cancel the warm-all run?',
+ description:
+ 'The warmer stops dispatching new teams at its next heartbeat and finishes the teams already in flight. Already-warmed caches are kept.',
+ shouldAwaitSubmit: true,
+ primaryButton: {
+ children: 'Cancel run',
+ status: 'danger',
+ onClick: async () => await cancelWarmRun(),
+ },
+ secondaryButton: {
+ children: 'Keep running',
+ },
+ })
+ }
+ >
+ Cancel run
+ </LemonButton>
+ )}
+ </div>
+ <LemonProgress percent={percent} />
+ <div className="flex items-center gap-2 text-secondary">
+ <span>
+ {warmRun.processed.toLocaleString()}/{warmRun.total.toLocaleString()} teams ({percent}%) ·{' '}
+ {warmRun.successful.toLocaleString()} ok, {warmRun.failed.toLocaleString()} failed
+ </span>
+ <span className="flex items-baseline gap-1 ml-auto">
+ Last heartbeat
+ <TZLabel time={warmRun.updated_at} />
+ </span>
+ </div>
+ {warmRun.is_stale && (
+ <LemonBanner type="warning">
+ This run stopped reporting progress. The warmer process likely died (deploy, OOM, or manual kill)
+ without writing a final state. Re-run the warmer to continue; its status shows the last dispatched
+ team id ({warmRun.last_team_id ?? 'unknown'}) as a resume cursor.
+ </LemonBanner>
+ )}
+ </div>
+ )
+}
+
function CacheStatusCell({ status, onView }: { status?: StaffCacheEntryStatus; onView: () => void }): JSX.Element {
const tag = !status ? (
<LemonTag type="muted">Unknown</LemonTag>
@@ -120,6 +224,8 @@ export function StaffCacheToolsTab(): JSX.Element {
return (
<div className="space-y-4">
+ <WarmRunPanel />
+
<StaffTeamSearchInput />
<div className="flex flex-wrap items-center gap-2 mt-2">
diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
index 048ac8ea9e7d..0d85501718da 100644
--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
@@ -30,6 +30,7 @@ describe('featureFlagsStaffToolsLogic', () => {
get: {
'/api/feature_flags_staff_teams': { results: [TEAM] },
'/api/feature_flags_staff_cache': { results: [] },
+ '/api/feature_flags_staff_cache/warm_run': { run: null },
},
})
initKeaTests()
@@ -195,6 +196,95 @@ describe('featureFlagsStaffToolsLogic', () => {
})
})
+ describe('warm-all run status', () => {
+ const WARM_RUN = {
+ run_id: 'run-1',
+ state: 'running',
+ scope: 'teams_with_flags',
+ total: 100,
+ processed: 40,
+ successful: 39,
+ failed: 1,
+ last_team_id: 4321,
+ started_at: '2026-07-09T00:00:00+00:00',
+ updated_at: '2026-07-09T00:10:00+00:00',
+ is_stale: false,
+ cancel_requested: false,
+ }
+
+ it('unwraps the run from the status endpoint response', async () => {
+ // Let the mount-time load (mocked as { run: null }) settle first so the
+ // assertion below unambiguously matches the reload with the new mock.
+ await expectLogic(logic).toDispatchActions(['loadWarmRunSuccess'])
+ useMocks({ get: { '/api/feature_flags_staff_cache/warm_run': { run: WARM_RUN } } })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadWarmRun()
+ })
+ .toDispatchActions(['loadWarmRun', 'loadWarmRunSuccess'])
+ .toMatchValues({ warmRun: WARM_RUN })
+ })
+
+ it('reads an absent run as null, not as the wrapper object', async () => {
+ logic.actions.loadWarmRun()
+ await expectLogic(logic).toDispatchActions(['loadWarmRunSuccess']).toMatchValues({ warmRun: null })
+ })
+
+ it('refetches status after a cancel request so the UI reflects it promptly', async () => {
+ useMocks({
+ post: {
+ '/api/feature_flags_staff_cache/warm_run/cancel': { run_id: 'run-1', cancel_requested: true },
+ },
+ })
+
+ logic.actions.cancelWarmRun()
+ await expectLogic(logic).toDispatchActions(['cancelWarmRunSuccess', 'loadWarmRun'])
+ expect(lemonToast.success).toHaveBeenCalled()
+ })
+
+ it('shows an error toast when the cancel request fails', async () => {
+ useMocks({ post: { '/api/feature_flags_staff_cache/warm_run/cancel': () => [400, {}] } })
+
+ logic.actions.cancelWarmRun()
+ await expectLogic(logic).toDispatchActions(['cancelWarmRunFailure'])
+ expect(lemonToast.error).toHaveBeenCalled()
+ })
+
+ it('polls at the active cadence while a run is live, and falls back to idle otherwise', async () => {
+ // Let the mount-time load (mocked as { run: null }, idle cadence) settle first.
+ await expectLogic(logic).toDispatchActions(['loadWarmRunSuccess'])
+
+ useMocks({ get: { '/api/feature_flags_staff_cache/warm_run': { run: WARM_RUN } } })
+ logic.actions.loadWarmRun()
+ await expectLogic(logic).toDispatchActions(['loadWarmRunSuccess'])
+ expect(logic.cache.warmRunPollMs).toEqual(5000)
+
+ // A stale "running" run is treated as idle, same as a completed/cancelled one.
+ useMocks({ get: { '/api/feature_flags_staff_cache/warm_run': { run: { ...WARM_RUN, is_stale: true } } } })
+ logic.actions.loadWarmRun()
+ await expectLogic(logic).toDispatchActions(['loadWarmRunSuccess'])
+ expect(logic.cache.warmRunPollMs).toEqual(30000)
+ })
+
+ it('falls back to the idle poll cadence when a status fetch fails', async () => {
+ // Let the mount-time load (mocked as { run: null }) settle first so it can't race
+ // with the loads below.
+ await expectLogic(logic).toDispatchActions(['loadWarmRunSuccess'])
+
+ // Put the poller into the active cadence first, so a no-op failure handler would be
+ // observable (staying at 5000) instead of masked by the idle default from mount.
+ useMocks({ get: { '/api/feature_flags_staff_cache/warm_run': { run: WARM_RUN } } })
+ logic.actions.loadWarmRun()
+ await expectLogic(logic).toDispatchActions(['loadWarmRunSuccess'])
+ expect(logic.cache.warmRunPollMs).toEqual(5000)
+
+ useMocks({ get: { '/api/feature_flags_staff_cache/warm_run': () => [500, {}] } })
+ logic.actions.loadWarmRun()
+ await expectLogic(logic).toDispatchActions(['loadWarmRunFailure'])
+ expect(logic.cache.warmRunPollMs).toEqual(30000)
+ })
+ })
+
describe('team search loader', () => {
it('does not query below the minimum search length', async () => {
logic.actions.searchTeams({ query: 'a' })
diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
index 183550811fbd..be756831aed2 100644
--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
@@ -1,4 +1,4 @@
-import { actions, kea, listeners, path, reducers, selectors } from 'kea'
+import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
@@ -11,6 +11,8 @@ import {
featureFlagsStaffCacheRebuildCreate,
featureFlagsStaffTeamConfigList,
featureFlagsStaffTeamConfigSetCreate,
+ featureFlagsStaffCacheWarmRunCancelCreate,
+ featureFlagsStaffCacheWarmRunRetrieve,
featureFlagsStaffTeamsList,
} from '../generated/api'
import type {
@@ -21,6 +23,8 @@ import type {
StaffCacheTeamStatusApi,
StaffTeamConfigApi,
StaffTeamResultApi,
+ StaffWarmRunApi,
+ StaffWarmRunCancelResponseApi,
} from '../generated/api.schemas'
import type { featureFlagsStaffToolsLogicType } from './featureFlagsStaffToolsLogicType'
@@ -38,12 +42,18 @@ export const CACHE_LABELS: Record<StaffReadableCacheKind, string> = {
const MIN_SEARCH_LENGTH = 2
const SEARCH_DEBOUNCE_MS = 300
+// Warm-all runs take hours; poll fast enough to feel live while one is running,
+// and slowly otherwise (a new run can only appear when an operator starts one).
+const WARM_RUN_ACTIVE_POLL_MS = 5000
+const WARM_RUN_IDLE_POLL_MS = 30000
+
export type StaffTeamResult = StaffTeamResultApi
export type StaffCacheTeamStatus = StaffCacheTeamStatusApi
export type StaffCacheEntryStatus = StaffCacheTeamStatusApi['evaluation']
export type StaffCacheMutationResponse = StaffCacheMutationResponseApi
export type StaffCacheEntry = StaffCacheEntryResponseApi
export type StaffTeamConfig = StaffTeamConfigApi
+export type StaffWarmRun = StaffWarmRunApi
export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>([
path(['products', 'feature_flags', 'frontend', 'staff', 'featureFlagsStaffToolsLogic']),
@@ -136,6 +146,23 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(
},
},
],
+ warmRun: [
+ null as StaffWarmRun | null,
+ {
+ loadWarmRun: async () => {
+ const response = await featureFlagsStaffCacheWarmRunRetrieve()
+ return response.run ?? null
+ },
+ },
+ ],
+ warmRunCancelResult: [
+ null as StaffWarmRunCancelResponseApi | null,
+ {
+ cancelWarmRun: async () => {
+ return await featureFlagsStaffCacheWarmRunCancelCreate()
+ },
+ },
+ ],
})),
reducers({
selectedTeamIds: [
@@ -224,6 +251,18 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(
actions.loadCacheStatus()
}
+ // Re-register the poller only when the desired cadence changes, so each
+ // tick doesn't churn the interval.
+ const scheduleWarmRunPoll = (desiredMs: number): void => {
+ if (cache.warmRunPollMs !== desiredMs) {
+ cache.warmRunPollMs = desiredMs
+ cache.disposables.add(() => {
+ const pollTimer = window.setInterval(() => actions.loadWarmRun(), desiredMs)
+ return () => clearInterval(pollTimer)
+ }, 'warmRunPoll')
+ }
+ }
+
return {
setSelectedTeamIds: () => {
actions.loadCacheStatus()
@@ -278,8 +317,31 @@ export const featureFlagsStaffToolsLogic = kea<featureFlagsStaffToolsLogicType>(
actions.teamConfigMutationSettled(teamId)
}
},
+ loadWarmRunSuccess: ({ warmRun }) => {
+ const desiredMs =
+ warmRun?.state === 'running' && !warmRun.is_stale ? WARM_RUN_ACTIVE_POLL_MS : WARM_RUN_IDLE_POLL_MS
+ scheduleWarmRunPoll(desiredMs)
+ },
+ loadWarmRunFailure: () => {
+ // A transient fetch error shouldn't permanently stop polling: fall back to the
+ // idle cadence so the panel keeps retrying instead of going stale forever.
+ scheduleWarmRunPoll(WARM_RUN_IDLE_POLL_MS)
+ },
+ cancelWarmRunSuccess: () => {
+ lemonToast.success(
+ 'Cancellation requested. The warmer stops dispatching new teams at its next heartbeat.'
+ )
+ actions.loadWarmRun()
+ },
+ cancelWarmRunFailure: () => {
+ lemonToast.error('Failed to request warm-run cancellation.')
+ actions.loadWarmRun()
+ },
}
}),
+ afterMount(({ actions }) => {
+ actions.loadWarmRun()
+ }),
urlToAction(({ actions, values }) => ({
'/feature_flags/staff': (_, searchParams) => {
// Team-admin deep link: seed the selected team and resolve its display info
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index 5d0f06dfa2a5..022fbd039624 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -285,6 +285,12 @@ tools:
feature-flags-staff-cache-rebuild-create:
operation: feature_flags_staff_cache_rebuild_create
enabled: false
+ feature-flags-staff-cache-warm-run-cancel-create:
+ operation: feature_flags_staff_cache_warm_run_cancel_create
+ enabled: false
+ feature-flags-staff-cache-warm-run-retrieve:
+ operation: feature_flags_staff_cache_warm_run_retrieve
+ enabled: false
feature-flags-staff-team-config-list:
operation: feature_flags_staff_team_config_list
enabled: false
diff --git a/rust/feature-flags/src/bin/warm-flags-cache.rs b/rust/feature-flags/src/bin/warm-flags-cache.rs
index 3add2bf0660e..58bb29d787a2 100644
--- a/rust/feature-flags/src/bin/warm-flags-cache.rs
+++ b/rust/feature-flags/src/bin/warm-flags-cache.rs
@@ -15,6 +15,9 @@ use tracing_subscriber::EnvFilter;
use feature_flags::flags::cache_builder::build_flags_cache;
use feature_flags::flags::cache_writer::{build_writer, persist_flags_cache};
+use feature_flags::flags::warm_run_status::{
+ is_active, read_current_status, WarmRunReporter, WarmRunState,
+};
use feature_flags::server::create_redis_client;
common_alloc::used!();
@@ -62,6 +65,19 @@ struct Cli {
/// don't accidentally write flags-cache entries into the shared Redis tier.
#[arg(long)]
allow_default_redis: bool,
+
+ /// Disable publishing run status to the flags Redis. Status is published by
+ /// default for full-scan runs (no explicit team IDs) so the staff cache tools
+ /// page can show live progress; targeted `--team-ids` runs never publish, as
+ /// they shouldn't claim the global warm-all status slot.
+ #[arg(long)]
+ no_report_status: bool,
+
+ /// Start even when the status blob shows another warm-all run as active.
+ /// The guard is heartbeat-based (a run whose status stopped updating is
+ /// considered dead), so this is only needed to race a genuinely live run.
+ #[arg(long)]
+ force: bool,
}
#[derive(Envconfig)]
@@ -164,7 +180,7 @@ async fn main() {
let writer = Arc::new(
build_writer(
- redis_client,
+ redis_client.clone(),
&infra.object_storage_region,
&infra.object_storage_bucket,
Some(infra.object_storage_endpoint.as_str()),
@@ -178,13 +194,71 @@ async fn main() {
return;
}
+ let reporter = build_reporter(&cli, &plan, redis_client).await;
+
tracing::info!(
"Warming flags cache for {} teams (concurrency: {})",
plan.total,
cli.concurrency
);
- run_warm(plan, writer, pg_reader, &cli).await;
+ run_warm(plan, writer, pg_reader, &cli, reporter).await;
+}
+
+/// Build the status reporter for full-scan runs, guarding against a second
+/// concurrent warm-all. The guard is check-then-write over the status blob —
+/// two operators starting within one heartbeat of each other can both pass,
+/// which only wastes duplicate (idempotent) work, so a lock key isn't worth it.
+async fn build_reporter(
+ cli: &Cli,
+ plan: &TeamPlan,
+ redis: Arc<dyn common_redis::Client + Send + Sync>,
+) -> Option<WarmRunReporter> {
+ let TeamSource::DatabaseScan { all_teams } = &plan.source else {
+ return None;
+ };
+ if cli.no_report_status {
+ return None;
+ }
+
+ if let Some(current) = read_current_status(&redis)
+ .await
+ .filter(|status| is_active(status, chrono::Utc::now()))
+ {
+ if !cli.force {
+ tracing::error!(
+ run_id = current.run_id,
+ started_at = %current.started_at,
+ processed = current.processed,
+ total = current.total,
+ "Another warm-all run appears active (heartbeat is fresh). \
+ Wait for it, cancel it from the staff cache tools page, or pass --force."
+ );
+ std::process::exit(1);
+ }
+ tracing::warn!(
+ run_id = current.run_id,
+ "Another warm-all run appears active; continuing due to --force"
+ );
+ }
+
+ let scope = if *all_teams {
+ "all_teams"
+ } else {
+ "teams_with_flags"
+ };
+ let run_id = uuid::Uuid::new_v4().to_string();
+ tracing::info!(
+ run_id,
+ scope,
+ "Publishing warm-run status to the flags Redis"
+ );
+ Some(WarmRunReporter::new(
+ redis,
+ run_id,
+ scope.to_string(),
+ plan.total,
+ ))
}
/// Coordinates the warm loop with bounded in-flight tasks and progress logging.
@@ -193,6 +267,7 @@ async fn run_warm(
writer: Arc<HyperCacheWriter>,
pg_reader: PostgresReader,
cli: &Cli,
+ mut reporter: Option<WarmRunReporter>,
) {
let total = plan.total;
let start = Instant::now();
@@ -237,8 +312,28 @@ async fn run_warm(
}
};
+ if let Some(r) = reporter.as_mut() {
+ r.start().await;
+ }
+ let mut cancelled = false;
+ let mut last_dispatched: Option<TeamId> = None;
+
let mut team_stream = TeamIdStream::new(plan, pg_reader.clone());
while let Some(team_id) = team_stream.next().await {
+ // Status heartbeat + cancel poll. No-op (no Redis traffic) until the
+ // report interval elapses, so this stays off the per-team hot path.
+ if let Some(r) = reporter.as_mut() {
+ r.record(completed, successful, failed, last_dispatched);
+ if r.maybe_report().await {
+ cancelled = true;
+ tracing::warn!(
+ run_id = r.run_id(),
+ "Cancellation requested; draining in-flight tasks"
+ );
+ break;
+ }
+ }
+
// Cap in-flight tasks at `concurrency`; combined with the seek-paged team-ID
// stream, peak memory stays O(concurrency + page size) regardless of team count.
if join_set.len() >= cli.concurrency {
@@ -258,6 +353,7 @@ async fn run_warm(
let pg = pg_reader.clone();
let writer = writer.clone();
let ttl_seconds = compute_ttl(cli);
+ last_dispatched = Some(team_id);
join_set.spawn(async move {
warm_team(pg, &writer, team_id, ttl_seconds)
.await
@@ -275,14 +371,38 @@ async fn run_warm(
);
}
+ if let Some(r) = reporter.as_mut() {
+ r.record(completed, successful, failed, last_dispatched);
+ if !cancelled && r.cancel_requested().await {
+ cancelled = true;
+ }
+ let final_state = if cancelled {
+ WarmRunState::Cancelled
+ } else {
+ WarmRunState::Completed
+ };
+ r.finish(final_state).await;
+ }
+
let duration = start.elapsed();
- tracing::info!(
- successful,
- failed,
- total,
- duration_secs = duration.as_secs_f64(),
- "Cache warming complete"
- );
+ if cancelled {
+ tracing::warn!(
+ successful,
+ failed,
+ completed,
+ total,
+ duration_secs = duration.as_secs_f64(),
+ "Cache warming cancelled before completion"
+ );
+ } else {
+ tracing::info!(
+ successful,
+ failed,
+ total,
+ duration_secs = duration.as_secs_f64(),
+ "Cache warming complete"
+ );
+ }
if failed > 0 {
std::process::exit(1);
@@ -594,6 +714,8 @@ mod tests {
no_stagger,
all_teams: false,
allow_default_redis: false,
+ no_report_status: false,
+ force: false,
}
}
diff --git a/rust/feature-flags/src/flags/mod.rs b/rust/feature-flags/src/flags/mod.rs
index a3a8631d4160..68cbdbd23fc0 100644
--- a/rust/feature-flags/src/flags/mod.rs
+++ b/rust/feature-flags/src/flags/mod.rs
@@ -16,6 +16,7 @@ pub mod flag_property_group;
pub mod flag_request;
pub mod flag_service;
pub mod property_filter;
+pub mod warm_run_status;
#[cfg(test)]
mod test_flag_matching;
diff --git a/rust/feature-flags/src/flags/warm_run_status.rs b/rust/feature-flags/src/flags/warm_run_status.rs
new file mode 100644
index 000000000000..cc897283cd4c
--- /dev/null
+++ b/rust/feature-flags/src/flags/warm_run_status.rs
@@ -0,0 +1,403 @@
+//! Run-state reporting for bulk flag-cache warming.
+//!
+//! The warmer publishes a JSON status blob into the flags Redis so the Django
+//! staff API (`products/feature_flags/backend/api/staff_cache.py`) can show
+//! live progress of a warm-all run and request cancellation, regardless of
+//! where the run was started (staff UI in the future, a jumphost shell today).
+//!
+//! Interop contract: values are written through the client's default value
+//! format (pickle + zstd), which mirrors Django's `flags_dedicated` cache
+//! (`django_redis` + `ZstdCompressor`), so Django reads the blob with a plain
+//! `caches["flags_dedicated"].get(...)` and vice versa for the cancel key.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use chrono::{DateTime, Utc};
+use common_redis::{Client, CustomRedisError};
+use serde::{Deserialize, Serialize};
+
+/// Full Redis keys. django-redis addresses keys as `KEY_PREFIX:VERSION:key`
+/// ("posthog:1:" in our config), so the Django-relative keys are
+/// `feature_flags/warm_run/status` and `feature_flags/warm_run/cancel`.
+pub const WARM_RUN_STATUS_KEY: &str = "posthog:1:feature_flags/warm_run/status";
+pub const WARM_RUN_CANCEL_KEY: &str = "posthog:1:feature_flags/warm_run/cancel";
+
+/// Status outlives the run so the staff page can show the last outcome.
+const STATUS_TTL_SECONDS: u64 = 7 * 24 * 3600;
+
+/// Minimum interval between status writes; also the cancel-poll cadence.
+/// Doubles as the heartbeat period — a running status whose `updated_at` is
+/// much older than this means the warmer process died.
+pub const REPORT_INTERVAL: Duration = Duration::from_secs(5);
+
+/// A `running` status with a heartbeat older than this is treated as a dead
+/// run (the process was killed without writing a final state): the start
+/// guard lets a new run overwrite it, and the Django staff API flags it as
+/// stale. Keep in sync with WARM_RUN_HEARTBEAT_STALE_SECONDS in
+/// `products/feature_flags/backend/api/staff_cache.py`. At a 5s heartbeat,
+/// 120s of silence is 24 missed beats — far beyond any Redis blip.
+pub const HEARTBEAT_STALE_AFTER_SECONDS: i64 = 120;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum WarmRunState {
+ Running,
+ Completed,
+ Cancelled,
+}
+
+/// The status blob as stored in Redis. Field names are a contract with the
+/// Django staff API serializer — change them in lockstep.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WarmRunStatus {
+ pub run_id: String,
+ pub state: WarmRunState,
+ /// Which team scope the run covers: "all_teams" or "teams_with_flags".
+ pub scope: String,
+ pub total: usize,
+ pub processed: usize,
+ pub successful: usize,
+ pub failed: usize,
+ /// Highest team id handed to a warm task so far. A resume from this cursor
+ /// can skip up to `concurrency` teams that were in flight when the process
+ /// died; their per-team failures are logged and self-heal on the next
+ /// organic invalidation or TTL refresh.
+ pub last_team_id: Option<i32>,
+ /// Epoch seconds. Serialized as integers (not RFC3339) so the Django
+ /// reader never has to parse chrono's nanosecond-precision timestamps.
+ #[serde(with = "chrono::serde::ts_seconds")]
+ pub started_at: DateTime<Utc>,
+ /// Heartbeat: bumped on every status write while running. Epoch seconds.
+ #[serde(with = "chrono::serde::ts_seconds")]
+ pub updated_at: DateTime<Utc>,
+}
+
+/// Read the current status blob, if any. A missing key or an unparseable blob
+/// (e.g. written by a newer/older binary) both read as "no run".
+pub async fn read_current_status(redis: &Arc<dyn Client + Send + Sync>) -> Option<WarmRunStatus> {
+ match redis.get(WARM_RUN_STATUS_KEY.to_string()).await {
+ Ok(raw) => match serde_json::from_str::<WarmRunStatus>(&raw) {
+ Ok(status) => Some(status),
+ Err(e) => {
+ tracing::warn!(error = %e, "Ignoring unparseable warm-run status blob");
+ None
+ }
+ },
+ Err(CustomRedisError::NotFound) => None,
+ Err(e) => {
+ tracing::warn!(error = %e, "Failed to read warm-run status");
+ None
+ }
+ }
+}
+
+/// True when `status` describes a run that still appears to be alive: state is
+/// `running` and the heartbeat is fresher than [`HEARTBEAT_STALE_AFTER_SECONDS`].
+pub fn is_active(status: &WarmRunStatus, now: DateTime<Utc>) -> bool {
+ status.state == WarmRunState::Running
+ && (now - status.updated_at).num_seconds() <= HEARTBEAT_STALE_AFTER_SECONDS
+}
+
+/// Publishes run state to Redis with throttled writes and polls for
+/// cancellation. All Redis failures are best-effort: a status blip must never
+/// sink a multi-hour warm run, so errors log a warning and the run continues.
+pub struct WarmRunReporter {
+ redis: Arc<dyn Client + Send + Sync>,
+ status: WarmRunStatus,
+ last_write: Instant,
+}
+
+impl WarmRunReporter {
+ pub fn new(
+ redis: Arc<dyn Client + Send + Sync>,
+ run_id: String,
+ scope: String,
+ total: usize,
+ ) -> Self {
+ let now = Utc::now();
+ Self {
+ redis,
+ status: WarmRunStatus {
+ run_id,
+ state: WarmRunState::Running,
+ scope,
+ total,
+ processed: 0,
+ successful: 0,
+ failed: 0,
+ last_team_id: None,
+ started_at: now,
+ updated_at: now,
+ },
+ last_write: Instant::now(),
+ }
+ }
+
+ pub fn run_id(&self) -> &str {
+ &self.status.run_id
+ }
+
+ /// Publish the initial `running` status.
+ pub async fn start(&mut self) {
+ self.write().await;
+ }
+
+ /// Update in-memory counters. Cheap and sync — call freely from the warm
+ /// loop; the Redis write happens in [`Self::maybe_report`].
+ pub fn record(
+ &mut self,
+ processed: usize,
+ successful: usize,
+ failed: usize,
+ last_team_id: Option<i32>,
+ ) {
+ self.status.processed = processed;
+ self.status.successful = successful;
+ self.status.failed = failed;
+ if last_team_id.is_some() {
+ self.status.last_team_id = last_team_id;
+ }
+ }
+
+ /// If the report interval has elapsed, write the current status and poll
+ /// the cancel key. Returns true when cancellation was requested for this
+ /// run — the caller should stop dispatching new teams.
+ pub async fn maybe_report(&mut self) -> bool {
+ if self.last_write.elapsed() < REPORT_INTERVAL {
+ return false;
+ }
+ self.write().await;
+ self.cancel_requested().await
+ }
+
+ /// Publish the terminal state.
+ pub async fn finish(&mut self, state: WarmRunState) {
+ self.status.state = state;
+ self.write().await;
+ }
+
+ /// True when the cancel key holds this run's id. Values left over from
+ /// cancelling an earlier run don't match and are ignored.
+ pub async fn cancel_requested(&self) -> bool {
+ match self.redis.get(WARM_RUN_CANCEL_KEY.to_string()).await {
+ Ok(value) => value == self.status.run_id,
+ Err(CustomRedisError::NotFound) => false,
+ Err(e) => {
+ tracing::warn!(error = %e, "Failed to poll warm-run cancel key");
+ false
+ }
+ }
+ }
+
+ async fn write(&mut self) {
+ self.status.updated_at = Utc::now();
+ self.last_write = Instant::now();
+ let payload = match serde_json::to_string(&self.status) {
+ Ok(payload) => payload,
+ Err(e) => {
+ tracing::warn!(error = %e, "Failed to serialize warm-run status");
+ return;
+ }
+ };
+ if let Err(e) = self
+ .redis
+ .setex(WARM_RUN_STATUS_KEY.to_string(), payload, STATUS_TTL_SECONDS)
+ .await
+ {
+ tracing::warn!(error = %e, "Failed to write warm-run status");
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use common_redis::{MockRedisClient, MockRedisValue};
+
+ fn reporter_with(redis: MockRedisClient) -> WarmRunReporter {
+ WarmRunReporter::new(
+ Arc::new(redis),
+ "run-abc".to_string(),
+ "teams_with_flags".to_string(),
+ 100,
+ )
+ }
+
+ fn written_status(redis: &MockRedisClient) -> WarmRunStatus {
+ let calls = redis.get_calls();
+ let write = calls
+ .iter()
+ .rev()
+ .find(|c| c.op == "setex" && c.key == WARM_RUN_STATUS_KEY)
+ .expect("expected a setex on the status key");
+ match &write.value {
+ MockRedisValue::StringWithTTL(payload, ttl) => {
+ assert_eq!(*ttl, STATUS_TTL_SECONDS);
+ serde_json::from_str(payload).expect("status payload must be valid JSON")
+ }
+ other => panic!("expected StringWithTTL, got {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn start_publishes_running_status() {
+ let mut redis = MockRedisClient::new();
+ redis.set_ret(WARM_RUN_STATUS_KEY, Ok(()));
+ let redis = redis;
+
+ let mut reporter = reporter_with(redis.clone());
+ reporter.start().await;
+
+ let status = written_status(&redis);
+ assert_eq!(status.state, WarmRunState::Running);
+ assert_eq!(status.run_id, "run-abc");
+ assert_eq!(status.total, 100);
+ assert_eq!(status.processed, 0);
+ }
+
+ #[tokio::test]
+ async fn maybe_report_throttles_within_interval() {
+ let redis = MockRedisClient::new();
+ let mut reporter = reporter_with(redis.clone());
+ // last_write is now, so the interval has not elapsed.
+ let cancelled = reporter.maybe_report().await;
+ assert!(!cancelled);
+ assert!(
+ redis.get_calls().is_empty(),
+ "no Redis traffic expected inside the report interval"
+ );
+ }
+
+ #[tokio::test]
+ async fn maybe_report_writes_and_polls_after_interval() {
+ let mut redis = MockRedisClient::new();
+ redis.set_ret(WARM_RUN_STATUS_KEY, Ok(()));
+ let redis = redis;
+
+ let mut reporter = reporter_with(redis.clone());
+ reporter.record(50, 48, 2, Some(4321));
+ reporter.last_write = Instant::now() - REPORT_INTERVAL;
+
+ let cancelled = reporter.maybe_report().await;
+ assert!(!cancelled, "no cancel key set, so not cancelled");
+
+ let status = written_status(&redis);
+ assert_eq!(status.processed, 50);
+ assert_eq!(status.successful, 48);
+ assert_eq!(status.failed, 2);
+ assert_eq!(status.last_team_id, Some(4321));
+ }
+
+ #[tokio::test]
+ async fn cancel_only_honored_for_matching_run_id() {
+ let mut redis = MockRedisClient::new();
+ redis.get_ret(WARM_RUN_CANCEL_KEY, Ok("some-older-run".to_string()));
+ let reporter = reporter_with(redis);
+ assert!(!reporter.cancel_requested().await);
+
+ let mut redis = MockRedisClient::new();
+ redis.get_ret(WARM_RUN_CANCEL_KEY, Ok("run-abc".to_string()));
+ let reporter = reporter_with(redis);
+ assert!(reporter.cancel_requested().await);
+ }
+
+ #[tokio::test]
+ async fn cancel_absent_key_reads_as_not_cancelled() {
+ let reporter = reporter_with(MockRedisClient::new());
+ assert!(!reporter.cancel_requested().await);
+ }
+
+ #[tokio::test]
+ async fn finish_publishes_terminal_state() {
+ let mut redis = MockRedisClient::new();
+ redis.set_ret(WARM_RUN_STATUS_KEY, Ok(()));
+ let redis = redis;
+
+ let mut reporter = reporter_with(redis.clone());
+ reporter.record(100, 97, 3, Some(9999));
+ reporter.finish(WarmRunState::Completed).await;
+
+ let status = written_status(&redis);
+ assert_eq!(status.state, WarmRunState::Completed);
+ assert_eq!(status.processed, 100);
+ }
+
+ /// The JSON field names and state values are a contract with the Django
+ /// staff API — lock them down so a rename can't silently break the UI.
+ #[test]
+ fn status_json_shape_is_stable() {
+ let status = WarmRunStatus {
+ run_id: "r".to_string(),
+ state: WarmRunState::Running,
+ scope: "all_teams".to_string(),
+ total: 1,
+ processed: 0,
+ successful: 0,
+ failed: 0,
+ last_team_id: None,
+ started_at: Utc::now(),
+ updated_at: Utc::now(),
+ };
+ let value: serde_json::Value =
+ serde_json::from_str(&serde_json::to_string(&status).unwrap()).unwrap();
+ for field in [
+ "run_id",
+ "state",
+ "scope",
+ "total",
+ "processed",
+ "successful",
+ "failed",
+ "last_team_id",
+ "started_at",
+ "updated_at",
+ ] {
+ assert!(value.get(field).is_some(), "missing field {field}");
+ }
+ assert_eq!(value["state"], "running");
+ assert!(
+ value["started_at"].is_i64() && value["updated_at"].is_i64(),
+ "timestamps must serialize as epoch seconds for the Django reader"
+ );
+ assert_eq!(
+ serde_json::to_value(WarmRunState::Cancelled).unwrap(),
+ "cancelled"
+ );
+ assert_eq!(
+ serde_json::to_value(WarmRunState::Completed).unwrap(),
+ "completed"
+ );
+ }
+
+ #[test]
+ fn is_active_requires_running_state_and_fresh_heartbeat() {
+ let now = Utc::now();
+ let mut status = WarmRunStatus {
+ run_id: "r".to_string(),
+ state: WarmRunState::Running,
+ scope: "all_teams".to_string(),
+ total: 1,
+ processed: 0,
+ successful: 0,
+ failed: 0,
+ last_team_id: None,
+ started_at: now,
+ updated_at: now,
+ };
+ assert!(is_active(&status, now));
+
+ status.updated_at = now - chrono::Duration::seconds(HEARTBEAT_STALE_AFTER_SECONDS);
+ assert!(
+ is_active(&status, now),
+ "heartbeat exactly at the threshold matches the Django reader's `> stale` check"
+ );
+
+ status.updated_at = now - chrono::Duration::seconds(HEARTBEAT_STALE_AFTER_SECONDS + 1);
+ assert!(!is_active(&status, now), "stale heartbeat is not active");
+
+ status.updated_at = now;
+ status.state = WarmRunState::Completed;
+ assert!(!is_active(&status, now), "terminal state is not active");
+ }
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c0d35e1e1864..bc910d11aafe 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -26788,6 +26788,32 @@ export namespace Schemas {
refreshing: boolean;
}
+ /**
+ * * `all_teams` - all_teams
+ * * `teams_with_flags` - teams_with_flags
+ */
+ export type FlagsWarmRunScopeEnum = typeof FlagsWarmRunScopeEnum[keyof typeof FlagsWarmRunScopeEnum];
+
+
+ export const FlagsWarmRunScopeEnum = {
+ AllTeams: 'all_teams',
+ TeamsWithFlags: 'teams_with_flags',
+ } as const;
+
+ /**
+ * * `running` - running
+ * * `completed` - completed
+ * * `cancelled` - cancelled
+ */
+ export type FlagsWarmRunStateEnum = typeof FlagsWarmRunStateEnum[keyof typeof FlagsWarmRunStateEnum];
+
+
+ export const FlagsWarmRunStateEnum = {
+ Running: 'running',
+ Completed: 'completed',
+ Cancelled: 'cancelled',
+ } as const;
+
export interface FlakyTestItem {
/** Reconstructed pytest nodeid (the CI span name), e.g. 'posthog/api/test/test_event/TestEvents::test_x'. A stable grouping key, not a runnable selector — use `selector` to run or quarantine the test. */
nodeid: string;
@@ -56025,6 +56051,55 @@ export namespace Schemas {
results: StaffTeamResult[];
}
+ export interface StaffWarmRun {
+ /** Unique id of the warm-all run. */
+ run_id: string;
+ /** 'running' while the warmer is working, 'completed' when it finished (per-team failures are counted, not fatal), or 'cancelled' when a cancel request was honored.
+ *
+ * * `running` - running
+ * * `completed` - completed
+ * * `cancelled` - cancelled */
+ state: FlagsWarmRunStateEnum;
+ /** Which teams the run covers: every team, or only teams that have ever had a flag.
+ *
+ * * `all_teams` - all_teams
+ * * `teams_with_flags` - teams_with_flags */
+ scope: FlagsWarmRunScopeEnum;
+ /** Number of teams the run will warm. */
+ total: number;
+ /** Teams processed so far (successful + failed). */
+ processed: number;
+ /** Teams whose evaluation cache was rebuilt successfully. */
+ successful: number;
+ /** Teams whose rebuild failed; details are in the warmer's logs. */
+ failed: number;
+ /**
+ * Highest team id dispatched so far — a resume cursor for operators re-running the warmer.
+ * @nullable
+ */
+ last_team_id: number | null;
+ /** When the run started. */
+ started_at: string;
+ /** Heartbeat: last time the warmer reported progress. */
+ updated_at: string;
+ /** True when the run claims to be running but its heartbeat stopped — the warmer process likely died without writing a final state. */
+ is_stale: boolean;
+ /** True when a cancel has been requested for this run but the warmer has not yet honored it. */
+ cancel_requested: boolean;
+ }
+
+ export interface StaffWarmRunCancelResponse {
+ /** Id of the run the cancel request targets. */
+ run_id: string;
+ /** Always true on success. */
+ cancel_requested: boolean;
+ }
+
+ export interface StaffWarmRunResponse {
+ /** Most recent warm-all run, or null when none has been recorded (or the dedicated flags cache is not configured). */
+ run: StaffWarmRun | null;
+ }
+
/**
* Response containing a JWT token (and resolved base URL) for reading a task run's live event stream
*/