:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): self-heal missing flag-definitions cache (#67174)
Patricio5ac94d9c99e3
diff --git a/posthog/storage/hypercache_manager.py b/posthog/storage/hypercache_manager.pyindex ab76718ec066..fc8e0b0e0b0e 100644--- a/posthog/storage/hypercache_manager.py+++ b/posthog/storage/hypercache_manager.py@@ -202,6 +202,19 @@ class HyperCacheManagementConfig:# Called once per batch for efficiency (avoids N+1 queries).get_team_ids_to_skip_fix_fn: Callable[[list[int]], set[int]] | None = None+ # When True, a full cache_miss is repaired even for a team in the grace period.+ # Only set for caches with no read-through DB fallback, where a miss is a hard+ # user-facing failure (the Rust /flags/definitions endpoint 503s). Read-through+ # caches (flags, team_metadata) cold-load on miss, so they keep the grace-period+ # skip as an optimization and leave this False.+ repair_miss_during_grace_period: bool = False++ # Optional write guard: given (key, payload), returns True to skip the write. Used+ # to veto caching an emptied group_type_mapping over populated data when personhog+ # lags. Applied by the verifier's direct db_data write and the self-heal drain; a+ # veto is neither a fix nor a failure. `update_fn` paths already guard internally.+ should_skip_write: Callable[[Any, dict], bool] | None = None+# Derived properties (computed from required properties using conventions)@propertydef namespace(self) -> str:diff --git a/posthog/storage/hypercache_verifier.py b/posthog/storage/hypercache_verifier.pyindex 903acb44eb81..4c2dd9c26910 100644--- a/posthog/storage/hypercache_verifier.py+++ b/posthog/storage/hypercache_verifier.py@@ -251,8 +251,15 @@ def _verify_and_fix_batch(issue_type = "expiry_missing"if issue_type:- # Check if we should skip fixing (e.g., grace period for recently updated flags)- if team.id in team_ids_to_skip_fix:+ # The grace period guards against clobbering an in-flight async rebuild,+ # which only matters when an entry EXISTS (mismatch/expiry). A full+ # cache_miss has nothing to clobber and hard-fails no-DB-fallback readers+ # (e.g. the Rust /flags/definitions endpoint → 503). This routine is shared+ # by every hypercache, so the miss exemption is opt-in per config: only the+ # flag_definitions caches set repair_miss_during_grace_period; read-through+ # caches (flags, team_metadata) cold-load on miss and keep the skip.+ repair_miss = issue_type == "cache_miss" and config.repair_miss_during_grace_period+ if not repair_miss and team.id in team_ids_to_skip_fix:result.skipped_for_grace_period += 1if len(result.skipped_team_ids) < MAX_FIXED_TEAM_IDS_TO_LOG:result.skipped_team_ids.append(team.id)@@ -307,6 +314,11 @@ def _fix_and_record(try:# Use preloaded db_data if available to avoid redundant DB queryif "db_data" in verification:+ # The direct write bypasses update_fn's internal guards, so apply the+ # config's write guard here too (e.g. refuse to cache an emptied+ # group_type_mapping over populated data). A veto is neither fix nor failure.+ if config.should_skip_write is not None and config.should_skip_write(team, verification["db_data"]):+ returnconfig.hypercache.set_cache_value(team, verification["db_data"])success = Trueelse:diff --git a/posthog/storage/test/test_hypercache_verifier.py b/posthog/storage/test/test_hypercache_verifier.pyindex 041ac1e8789d..1a72663aa837 100644--- a/posthog/storage/test/test_hypercache_verifier.py+++ b/posthog/storage/test/test_hypercache_verifier.py@@ -127,6 +127,7 @@ class TestFixAndRecord(BaseTest):def test_successful_fix_increments_correct_counter(self, issue_type, expected_counter):"""Test that successful fix increments the correct counter for each issue type."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.update_fn.return_value = Trueresult = VerificationResult()@@ -153,6 +154,7 @@ class TestFixAndRecord(BaseTest):def test_failed_fix_increments_fix_failed(self):"""Test that failed fix increments fix_failed counter."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.update_fn.return_value = Falseresult = VerificationResult()@@ -173,6 +175,7 @@ class TestFixAndRecord(BaseTest):def test_exception_in_update_fn_increments_fix_failed(self):"""Test that exception in update_fn increments fix_failed."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.update_fn.side_effect = Exception("Update failed")result = VerificationResult()@@ -192,6 +195,7 @@ class TestFixAndRecord(BaseTest):def test_uses_db_data_from_verification_directly(self):"""Test that _fix_and_record uses verification['db_data'] to set cache directly, bypassing update_fn."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guarddb_data = {"flags": ["flag1", "flag2"]}result = VerificationResult()@@ -211,6 +215,28 @@ class TestFixAndRecord(BaseTest):assert result.cache_miss_fixed == 1assert self.team.id in result.fixed_team_ids+ def test_db_data_write_skipped_when_should_skip_write_vetoes(self):+ """A config write guard (e.g. group_type_mapping emptied) vetoes the direct+ db_data write, counting neither a fix nor a failure."""+ mock_config = MagicMock()+ mock_config.should_skip_write.return_value = True+ db_data: dict = {"flags": [], "group_type_mapping": {}}++ result = VerificationResult()++ _fix_and_record(+ team=self.team,+ config=mock_config,+ issue_type="cache_miss",+ cache_type="test_cache",+ result=result,+ verification={"status": "miss", "db_data": db_data},+ )++ mock_config.hypercache.set_cache_value.assert_not_called()+ assert result.cache_miss_fixed == 0+ assert result.fix_failed == 0+@parameterized.expand([("empty_dict", {}),@@ -220,6 +246,7 @@ class TestFixAndRecord(BaseTest):def test_falls_back_to_update_fn_when_no_db_data_in_verification(self, _name, verification):"""Test that _fix_and_record falls back to update_fn when verification has no db_data."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.update_fn.return_value = Trueresult = VerificationResult()@@ -242,6 +269,7 @@ class TestFixAndRecord(BaseTest):def test_db_data_set_cache_value_exception_increments_fix_failed(self):"""Test that exceptions in set_cache_value (db_data path) increment fix_failed."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.set_cache_value.side_effect = Exception("Redis error")db_data = {"flags": ["flag1"]}@@ -267,6 +295,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_match_status_does_not_fix(self):"""Test that cache match status doesn't trigger a fix."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.hypercache.get_cache_identifier.return_value = str(self.team.id)@@ -300,6 +329,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_status_triggers_fix(self, status, issue, expected_counter):"""Test that miss/mismatch status triggers the appropriate fix."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.update_fn.return_value = True@@ -324,9 +354,52 @@ class TestVerifyAndFixBatch(BaseTest):# When db_batch_data is None (no batch_load_fn), it falls back to update_fnmock_config.update_fn.assert_called_once_with(self.team)+ @parameterized.expand(+ [+ # A no-DB-fallback cache (repair_miss_during_grace_period=True) must repair a+ # miss even in the grace period, or the reader 503s until the next sweep. A+ # read-through cache (False) keeps the skip since it cold-loads on miss.+ (True, True),+ (False, False),+ ]+ )+ def test_grace_period_repair_miss_is_config_gated(self, repair_miss_during_grace_period, expect_fixed):+ mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guard+ mock_config.hypercache.batch_load_fn = None+ mock_config.hypercache.batch_get_from_cache.return_value = {}+ mock_config.update_fn.return_value = True+ mock_config.repair_miss_during_grace_period = repair_miss_during_grace_period+ # Team IS inside the grace period (recently updated), with a full miss.+ mock_config.get_team_ids_to_skip_fix_fn.return_value = {self.team.id}++ result = VerificationResult()++ def verify_fn(team, db_batch_data, cache_batch_data):+ return {"status": "miss", "issue": "CACHE_MISS"}++ with patch("posthog.storage.hypercache_verifier.batch_check_expiry_tracking", return_value={}):+ _verify_and_fix_batch(+ teams=[self.team],+ config=mock_config,+ verify_team_fn=verify_fn,+ cache_type="test_cache",+ result=result,+ )++ if expect_fixed:+ assert result.cache_miss_fixed == 1+ assert result.skipped_for_grace_period == 0+ mock_config.update_fn.assert_called_once_with(self.team)+ else:+ assert result.cache_miss_fixed == 0+ assert result.skipped_for_grace_period == 1+ mock_config.update_fn.assert_not_called()+def test_expiry_missing_triggers_fix_for_match_status(self):"""Test that missing expiry tracking triggers fix even when cache matches."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.hypercache.get_cache_identifier.return_value = str(self.team.id)@@ -358,6 +431,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_verification_error_increments_errors(self):"""Test that verification errors are counted."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}@@ -381,6 +455,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_batch_load_fn_called_when_available(self) -> None:mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_db_batch_data: dict = {self.team.id: {"flags": []}}mock_config.hypercache.batch_load_fn.return_value = mock_db_batch_datamock_config.hypercache.batch_get_from_cache.return_value = {}@@ -417,6 +492,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_fix_uses_db_data_from_verification(self, _name, base_verification_result, expiry_status, result_attr):"""Test that fixes use db_data from verify_fn result to avoid redundant DB queries."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn.return_value = {self.team.id: {"flags": ["flag1", "flag2"]}}mock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.get_team_ids_to_skip_fix_fn = None@@ -444,6 +520,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_expiry_missing_fix_uses_batch_data_via_injection(self):"""Test that expiry_missing fixes use batch-loaded db_data even when verify_fn omits it."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn.return_value = {self.team.id: {"flags": ["flag1", "flag2"]}}mock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.hypercache.get_cache_identifier.return_value = str(self.team.id)@@ -481,6 +558,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_fix_uses_batch_data(self, _name, verification_result, expiry_status, result_attr):"""Test that fixes use preloaded batch data via set_cache_value when available."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guarddb_data = {"flags": ["flag1", "flag2"]}mock_db_batch_data: dict = {self.team.id: db_data}mock_config.hypercache.batch_load_fn.return_value = mock_db_batch_data@@ -510,6 +588,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_fix_falls_back_to_update_fn_without_batch_load(self):"""Test that fixes fall back to update_fn when batch_load_fn is not available."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.update_fn.return_value = True@@ -537,6 +616,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_batch_get_from_cache_error_falls_back_to_empty_dict(self):"""Test that batch_get_from_cache errors fall back to empty dict (individual lookups)."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.side_effect = Exception("Redis connection failed")mock_config.hypercache.get_cache_identifier.return_value = str(self.team.id)@@ -564,9 +644,11 @@ class TestVerifyAndFixBatch(BaseTest):assert result.total == 1assert result.errors == 0 # Should not count as error, just fallback- def test_get_team_ids_to_skip_fix_fn_skips_fix_for_full_verification(self):- """Test that get_team_ids_to_skip_fix_fn can skip fixes for teams with recent updates."""+ def test_get_team_ids_to_skip_fix_fn_skips_mismatch_fix(self):+ """A mismatch on a skip-listed (recently updated) team is left for the in-flight+ async rebuild. (A miss is the exception — see test_grace_period_repair_miss_is_config_gated.)"""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}# Return team ID in the skip set@@ -575,7 +657,7 @@ class TestVerifyAndFixBatch(BaseTest):result = VerificationResult()def verify_fn(team, db_batch_data, cache_batch_data):- return {"status": "miss", "issue": "CACHE_MISS"}+ return {"status": "mismatch", "issue": "DATA_MISMATCH"}with patch("posthog.storage.hypercache_verifier.batch_check_expiry_tracking", return_value={}):_verify_and_fix_batch(@@ -597,6 +679,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_get_team_ids_to_skip_fix_fn_none_does_not_skip(self):"""Test that when get_team_ids_to_skip_fix_fn is None, fixes proceed normally."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.get_team_ids_to_skip_fix_fn = None # No skip function@@ -625,6 +708,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_get_team_ids_to_skip_fix_fn_empty_set_does_not_skip(self):"""Test that when get_team_ids_to_skip_fix_fn returns empty set, fixes proceed."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.get_team_ids_to_skip_fix_fn.return_value = set() # Empty set - don't skip@@ -657,6 +741,7 @@ class TestVerifyAndFixAllTeams(BaseTest):def test_processes_all_teams_in_chunks(self):"""Test that all teams are processed in chunks."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.get_teams_queryset.return_value = Team.objects.all()mock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}@@ -679,6 +764,7 @@ class TestVerifyAndFixAllTeams(BaseTest):def test_returns_aggregated_results(self):"""Test that results are aggregated across all chunks."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.get_teams_queryset.return_value = Team.objects.all()mock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}@@ -710,6 +796,7 @@ class TestVerifyAndFixAllTeamsQuerysetScoping(BaseTest):team2 = Team.objects.create(organization=self.organization, name="Team 2")mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.get_teams_queryset.return_value = Team.objects.filter(id=team2.id)mock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}@@ -736,6 +823,7 @@ class TestVerifyAndFixAllTeamsQuerysetScoping(BaseTest):def test_empty_queryset_processes_zero_teams(self):"""When get_teams_queryset() returns empty queryset, no teams are verified."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.get_teams_queryset.return_value = Team.objects.none()mock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}@@ -756,6 +844,7 @@ class TestVerifyAndFixAllTeamsQuerysetScoping(BaseTest):def test_iterates_all_teams_when_queryset_fn_is_none(self):"""When get_teams_queryset() has no scoping function, all teams are verified."""mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guardmock_config.get_teams_queryset.return_value = Team.objects.all()mock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex ca6e5eaa6b55..b934044d853d 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -86,6 +86,7 @@ from products.feature_flags.backend.tasks import (cleanup_stale_flag_definitions_expiry_tracking_task,cleanup_stale_flags_expiry_tracking_task,compute_feature_flag_metrics,+ drain_flag_definitions_rebuild_requests,feature_flags_local_eval_canary_task,refresh_expiring_flag_definitions_cache_entries,refresh_expiring_flags_cache_entries,@@ -345,6 +346,17 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:expires_seconds=60 * 60,)+ # Flag definitions self-heal - every minute. Drains the queue the Rust+ # /flags/definitions endpoint fills on cache miss and rebuilds those caches,+ # so a missing entry heals in ~1 min instead of waiting for the hourly verifier.+ add_periodic_task_with_expiry(+ sender,+ crontab(minute="*"),+ drain_flag_definitions_rebuild_requests.s(),+ name="drain flag definitions rebuild requests",+ expires_seconds=60,+ )+# Feature flags local-eval canary - every 5 minutesadd_periodic_task_with_expiry(sender,diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex 8050379e5679..8ffa67eeac51 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -782,6 +782,12 @@ FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(cache_name="flag_definitions",get_teams_queryset_fn=get_teams_with_flags_queryset,get_team_ids_to_skip_fix_fn=get_team_ids_with_recently_updated_flags,+ # The Rust /flags/definitions reader has no DB fallback, so a miss must be+ # repaired even during the grace period rather than 503 until the next sweep.+ repair_miss_during_grace_period=True,+ # Guard the verifier's direct db_data write against caching an emptied+ # group_type_mapping (personhog lag), same as the signal-driven write path.+ should_skip_write=_skip_write_if_group_mapping_emptied,)FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(@@ -790,6 +796,8 @@ FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementCcache_name="flag_definitions_no_cohorts",get_teams_queryset_fn=get_teams_with_flags_queryset,get_team_ids_to_skip_fix_fn=get_team_ids_with_recently_updated_flags,+ repair_miss_during_grace_period=True,+ should_skip_write=_skip_write_if_group_mapping_emptied,)diff --git a/products/feature_flags/backend/rebuild_queue.py b/products/feature_flags/backend/rebuild_queue.pynew file mode 100644index 000000000000..3e909f8b2bd4--- /dev/null+++ b/products/feature_flags/backend/rebuild_queue.py@@ -0,0 +1,244 @@+"""+Self-heal queue for the flag-definitions HyperCache.++The Rust ``/flags/definitions`` endpoint reads cohort-inclusive flag definitions+straight from HyperCache with no DB fallback, so a missing entry returns 503 until+something rewrites it. On every such miss the Rust service enqueues the team into a+Redis sorted set (see ``rust/feature-flags/src/api/flag_definitions.rs``); this+module drains that set and rebuilds the cache, so a missing entry self-heals within+~1 minute instead of waiting for the hourly verifier or a manual rewarm.++Throttling keeps a permanently-failing team from being rebuilt on a loop:+- a per-team cooldown bounds attempts to one per ``COOLDOWN_SECONDS``, and+- a consecutive-failure circuit breaker stops attempts entirely for+ ``CIRCUIT_OPEN_SECONDS`` once a team fails ``CIRCUIT_OPEN_THRESHOLD`` times.++Both cache variants (with and without cohorts) are rebuilt, so a with-cohorts miss+heals the without-cohorts entry too. The drain exists for the mass-eviction backlog,+so it loads the whole batch in one DB round (like the verifier) rather than per team.+"""++import time++import redis as redis_lib+import structlog+from celery.exceptions import SoftTimeLimitExceeded+from prometheus_client import Counter, Gauge++from posthog.models.team import Team+from posthog.redis import get_client++from products.feature_flags.backend.local_evaluation import (+ _skip_write_if_group_mapping_emptied,+ flag_definitions_hypercache,+ flag_definitions_without_cohorts_hypercache,+)++logger = structlog.get_logger(__name__)++# Sorted set the Rust service writes misses to (member = team_id, score = enqueue+# time in epoch MILLIS). MUST match FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET in the+# Rust service.+REBUILD_REQUESTS_ZSET = "flag_definitions:rebuild_requests"++# Sorted set of teams with an open circuit (member = team_id, score = expiry epoch+# seconds). Doubles as the dead-letter gauge source via ZCARD after pruning.+CIRCUIT_ZSET = "flag_definitions:rebuild_circuit"++COOLDOWN_KEY = "flag_definitions:rebuild_cooldown:{team_id}"+FAILURE_STREAK_KEY = "flag_definitions:rebuild_fails:{team_id}"++# Each team's rebuild does two synchronous set_cache_value writes (Redis + a blocking+# S3 PUT), all sequential within the task's soft time limit. Kept conservative so a+# full drain stays well under that limit; leftover teams re-drain on the next tick.+DRAIN_BATCH_SIZE = 100+COOLDOWN_SECONDS = 300 # at most one rebuild attempt per team per 5 minutes+# Must stay > COOLDOWN_SECONDS * CIRCUIT_OPEN_THRESHOLD, or the streak key expires+# between cooldown windows and the circuit can never trip.+FAILURE_STREAK_TTL = 3600+CIRCUIT_OPEN_THRESHOLD = 5 # consecutive failures before we stop auto-retrying+CIRCUIT_OPEN_SECONDS = 3600 # how long a tripped circuit blocks auto-retry++REBUILD_PROCESSED = Counter(+ "posthog_flag_definitions_rebuild_processed",+ "Flag-definitions self-heal rebuilds drained from the queue",+ labelnames=["result"], # success | failure | skipped_cooldown | circuit_open+)+REBUILD_QUEUE_DEPTH = Gauge(+ "posthog_flag_definitions_rebuild_queue_depth",+ "Teams currently waiting in the flag-definitions rebuild queue",+)+REBUILD_OLDEST_AGE = Gauge(+ "posthog_flag_definitions_rebuild_oldest_age_seconds",+ # Score refreshes on every re-enqueue, so this is seconds since the oldest queued+ # team's most recent miss, not time-stuck. Read alongside queue_depth.+ "Seconds since the oldest queued team's most recent miss (read with queue_depth)",+)+REBUILD_DEAD_LETTER = Gauge(+ "posthog_flag_definitions_rebuild_dead_letter_teams",+ "Teams whose rebuild circuit is open (repeatedly failing)",+)+++def _parse_team_id(raw: bytes | str) -> int | None:+ """Members are written by Rust as the stringified team id; tolerate bytes/str."""+ try:+ return int(raw.decode() if isinstance(raw, bytes) else raw)+ except (ValueError, AttributeError):+ return None+++def _redis() -> redis_lib.Redis:+ # Derive from the HyperCache itself, not a standalone constant, so the queue can+ # never read a different Redis than the cache it heals.+ return get_client(flag_definitions_hypercache.redis_url)+++def drain_rebuild_requests(batch_size: int = DRAIN_BATCH_SIZE) -> dict[str, int]:+ """Drain the rebuild request set and rebuild each team's cache once.++ Returns a per-result count dict (also useful for tests).+ """+ redis = _redis()+ now = time.time()++ # Prune expired circuits first, then publish gauges for the dashboard.+ redis.zremrangebyscore(CIRCUIT_ZSET, "-inf", now)+ REBUILD_DEAD_LETTER.set(redis.zcard(CIRCUIT_ZSET))+ _emit_queue_gauges(redis, now)++ stats = {"success": 0, "failure": 0, "skipped_cooldown": 0, "circuit_open": 0}++ eligible: list[int] = []+ for raw in redis.zrange(REBUILD_REQUESTS_ZSET, 0, batch_size - 1):+ # Remove first: a still-missing team is re-enqueued by its next miss, so we+ # never drop a genuinely-needed rebuild, but we also don't spin on one entry.+ redis.zrem(REBUILD_REQUESTS_ZSET, raw)++ team_id = _parse_team_id(raw)+ if team_id is None:+ continue++ if redis.zscore(CIRCUIT_ZSET, str(team_id)) is not None:+ stats["circuit_open"] += 1+ REBUILD_PROCESSED.labels(result="circuit_open").inc()+ continue++ # Cooldown bounds attempts even while the team keeps polling and re-enqueuing.+ if not redis.set(COOLDOWN_KEY.format(team_id=team_id), 1, nx=True, ex=COOLDOWN_SECONDS):+ stats["skipped_cooldown"] += 1+ REBUILD_PROCESSED.labels(result="skipped_cooldown").inc()+ continue++ eligible.append(team_id)++ try:+ results = _rebuild_batch(redis, eligible)+ except SoftTimeLimitExceeded:+ # Winding down mid-batch. The cooldown was set up front (it doubles as a mutex+ # against overlapping drains), so un-rebuilt teams would otherwise wait out the+ # full 5-minute cooldown. Release the whole batch's cooldowns so the next drain+ # retries them in ~1 minute; already-rebuilt teams won't re-enqueue, so clearing+ # theirs too is harmless.+ for team_id in eligible:+ redis.delete(COOLDOWN_KEY.format(team_id=team_id))+ raise++ for ok in results.values():+ result = "success" if ok else "failure"+ stats[result] += 1+ REBUILD_PROCESSED.labels(result=result).inc()++ return stats+++def _emit_queue_gauges(redis: redis_lib.Redis, now: float) -> None:+ REBUILD_QUEUE_DEPTH.set(redis.zcard(REBUILD_REQUESTS_ZSET))+ oldest = redis.zrange(REBUILD_REQUESTS_ZSET, 0, 0, withscores=True)+ if oldest:+ # score is the most-recent enqueue time in epoch millis. Rust re-enqueues with+ # zadd (not NX), so a team polled every ~30s keeps its score refreshed: this is+ # "time since last miss", bounded by the SDK poll interval, not "time since first+ # miss". A small value is not proof the queue is healthy — read it with depth.+ _, score_ms = oldest[0]+ REBUILD_OLDEST_AGE.set(max(0.0, now - float(score_ms) / 1000.0))+ else:+ REBUILD_OLDEST_AGE.set(0)+++def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, bool]:+ """Rebuild every eligible team from a single batched DB load, then record each+ outcome. Mirrors the verifier: one batch_load_fn per variant, then set_cache_value+ per team (no per-team load_fn), which is the point of draining in one pass.++ A SoftTimeLimitExceeded propagates so the task winds down cleanly (the interrupted+ teams stay missing and are re-enqueued by their next miss). Any other load error+ fails the whole batch — a persistent outage still trips circuits after the usual+ consecutive-failure threshold rather than hammering the DB.+ """+ if not team_ids:+ return {}++ # Both flag_definitions caches are always constructed with a batch_load_fn; bind it+ # to narrow the Optional type and fail loudly if that invariant ever breaks.+ with_cohorts_load = flag_definitions_hypercache.batch_load_fn+ without_cohorts_load = flag_definitions_without_cohorts_hypercache.batch_load_fn+ if with_cohorts_load is None or without_cohorts_load is None:+ raise RuntimeError("flag_definitions hypercaches must be configured with a batch_load_fn")++ try:+ teams = list(Team.objects.filter(id__in=team_ids))+ teams_by_id = {team.id: team for team in teams}+ with_cohorts = with_cohorts_load(teams)+ without_cohorts = without_cohorts_load(teams)+ except SoftTimeLimitExceeded:+ raise+ except Exception:+ logger.exception("flag definitions self-heal batch load failed", team_count=len(team_ids))+ return {team_id: _record_result(redis, team_id, ok=False) for team_id in team_ids}++ results: dict[int, bool] = {}+ for team_id in team_ids:+ team = teams_by_id.get(team_id)+ if team is None:+ results[team_id] = _record_result(redis, team_id, ok=False)+ continue+ payload = with_cohorts[team_id]+ if _skip_write_if_group_mapping_emptied(team, payload):+ # personhog lag would cache an emptied group_type_mapping; skip both writes+ # without counting a failure (that would wrongly advance the circuit breaker).+ # Release the cooldown so the team retries on the next drain once the mapping+ # is available, rather than staying missing for the full cooldown window.+ redis.delete(COOLDOWN_KEY.format(team_id=team_id))+ continue+ try:+ flag_definitions_hypercache.set_cache_value(team, payload)+ flag_definitions_without_cohorts_hypercache.set_cache_value(team, without_cohorts[team_id])+ ok = True+ except SoftTimeLimitExceeded:+ raise+ except Exception:+ logger.exception("flag definitions self-heal rebuild failed", team_id=team_id)+ ok = False+ results[team_id] = _record_result(redis, team_id, ok=ok)+ return results+++def _record_result(redis: redis_lib.Redis, team_id: int, *, ok: bool) -> bool:+ """Track the failure streak and trip/clear the circuit for one team."""+ streak_key = FAILURE_STREAK_KEY.format(team_id=team_id)+ if ok:+ redis.delete(streak_key)+ redis.zrem(CIRCUIT_ZSET, str(team_id))+ return True++ streak = redis.incr(streak_key)+ redis.expire(streak_key, FAILURE_STREAK_TTL)+ if streak >= CIRCUIT_OPEN_THRESHOLD:+ redis.zadd(CIRCUIT_ZSET, {str(team_id): time.time() + CIRCUIT_OPEN_SECONDS})+ logger.warning(+ "flag definitions self-heal circuit opened",+ team_id=team_id,+ streak=streak,+ )+ return Falsediff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.pyindex 19f9c1452724..515c59a44650 100644--- a/products/feature_flags/backend/tasks.py+++ b/products/feature_flags/backend/tasks.py@@ -27,6 +27,7 @@ from products.feature_flags.backend.local_evaluation import (update_flag_caches,)from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.rebuild_queue import drain_rebuild_requestslogger = structlog.get_logger(__name__)@@ -47,6 +48,21 @@ def update_team_flags_cache(team_id: int) -> None:update_flag_caches(team)+# Bounded below the 1-minute schedule so a slow drain (e.g. a large post-eviction+# backlog rebuilt inline) can't run past the next tick and pin a worker. Teams not+# reached before the limit stay missing and are re-enqueued by their next miss.+@shared_task(+ ignore_result=True,+ queue=CeleryQueue.FEATURE_FLAGS.value,+ soft_time_limit=50,+ time_limit=55,+)+def drain_flag_definitions_rebuild_requests() -> None:+ """Drain the flag-definitions self-heal queue, rebuilding caches the Rust+ /flags/definitions endpoint reported missing. Scheduled every minute."""+ drain_rebuild_requests()++@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS.value)@skip_team_scope_auditdef update_team_service_flags_cache(team_id: int) -> None:diff --git a/products/feature_flags/backend/test/test_rebuild_queue.py b/products/feature_flags/backend/test/test_rebuild_queue.pynew file mode 100644index 000000000000..6c538723d279--- /dev/null+++ b/products/feature_flags/backend/test/test_rebuild_queue.py@@ -0,0 +1,200 @@+import time+from contextlib import contextmanager+from types import SimpleNamespace++import pytest+from unittest.mock import patch++import fakeredis+from celery.exceptions import SoftTimeLimitExceeded+from prometheus_client import REGISTRY++from products.feature_flags.backend import rebuild_queue+from products.feature_flags.backend.rebuild_queue import (+ CIRCUIT_OPEN_THRESHOLD,+ CIRCUIT_ZSET,+ COOLDOWN_KEY,+ FAILURE_STREAK_KEY,+ REBUILD_REQUESTS_ZSET,+ drain_rebuild_requests,+)+++def fake_redis():+ client = fakeredis.FakeRedis()+ with patch.object(rebuild_queue, "get_client", return_value=client):+ yield client+++@contextmanager+def _rebuilds(error=None, skip_write=False, load_error=None):+ """Patch the batch DB-load + cache-write seam so rebuilds succeed (error=None) or+ fail with the given exception, without touching the DB or the real caches.+ `skip_write=True` makes the group-mapping-emptied guard veto every write.+ `load_error` makes the batch DB load raise (simulating a DB/query failure)."""++ def _load(teams):+ if load_error is not None:+ raise load_error+ return {t.id: {} for t in teams}++ with (+ patch.object(rebuild_queue, "Team") as team,+ patch.object(rebuild_queue, "_skip_write_if_group_mapping_emptied", return_value=skip_write),+ patch.object(rebuild_queue.flag_definitions_hypercache, "batch_load_fn", new=_load),+ patch.object(rebuild_queue.flag_definitions_without_cohorts_hypercache, "batch_load_fn", new=_load),+ patch.object(rebuild_queue.flag_definitions_hypercache, "set_cache_value", side_effect=error) as set_cache,+ patch.object(rebuild_queue.flag_definitions_without_cohorts_hypercache, "set_cache_value", side_effect=error),+ ):+ team.objects.filter.side_effect = lambda id__in: [SimpleNamespace(id=int(t)) for t in id__in]+ yield set_cache+++def _enqueue(client, team_id, score=0):+ client.zadd(REBUILD_REQUESTS_ZSET, {str(team_id): score})+++def test_drain_rebuilds_queued_team_and_clears_it(fake_redis):+ _enqueue(fake_redis, 140414)+ with _rebuilds():+ stats = drain_rebuild_requests()++ assert stats["success"] == 1+ assert fake_redis.zcard(REBUILD_REQUESTS_ZSET) == 0+++def test_invalid_member_is_discarded_without_rebuild(fake_redis):+ fake_redis.zadd(REBUILD_REQUESTS_ZSET, {"not-an-int": 0})+ with _rebuilds():+ stats = drain_rebuild_requests()++ assert fake_redis.zcard(REBUILD_REQUESTS_ZSET) == 0+ assert stats == {"success": 0, "failure": 0, "skipped_cooldown": 0, "circuit_open": 0}+++def test_cooldown_prevents_a_second_rebuild_within_the_window(fake_redis):+ with _rebuilds():+ _enqueue(fake_redis, 1)+ first = drain_rebuild_requests()+ assert first["success"] == 1++ # Team is still missing, so its next miss re-enqueues it before the cooldown lapses.+ _enqueue(fake_redis, 1)+ stats = drain_rebuild_requests()++ assert stats["skipped_cooldown"] == 1+ assert stats["success"] == 0 # not retried during cooldown+++def test_circuit_opens_after_repeated_failures_then_skips(fake_redis):+ team_id = 7+ with _rebuilds(error=Exception("boom")):+ for _ in range(CIRCUIT_OPEN_THRESHOLD):+ _enqueue(fake_redis, team_id)+ drain_rebuild_requests()+ # Simulate the per-team cooldown lapsing before the next miss re-enqueues.+ fake_redis.delete(COOLDOWN_KEY.format(team_id=team_id))++ # Circuit is now open: a further request is skipped instead of rebuilt again.+ _enqueue(fake_redis, team_id)+ stats = drain_rebuild_requests()++ assert stats["circuit_open"] == 1+ assert fake_redis.zscore(CIRCUIT_ZSET, str(team_id)) is not None+++def test_successful_rebuild_after_circuit_expiry_clears_streak_and_circuit(fake_redis):+ team_id = 9+ with _rebuilds(error=Exception("boom")):+ for _ in range(CIRCUIT_OPEN_THRESHOLD):+ _enqueue(fake_redis, team_id)+ drain_rebuild_requests()+ fake_redis.delete(COOLDOWN_KEY.format(team_id=team_id))+ assert fake_redis.zscore(CIRCUIT_ZSET, str(team_id)) is not None+ assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=team_id)) is not None++ # Expire the circuit (score in the past) so the drain prunes it and retries, rather+ # than the test clearing it — otherwise this wouldn't exercise the success cleanup.+ fake_redis.zadd(CIRCUIT_ZSET, {str(team_id): 1.0})+ fake_redis.delete(COOLDOWN_KEY.format(team_id=team_id))+ _enqueue(fake_redis, team_id)+ with _rebuilds():+ stats = drain_rebuild_requests()++ assert stats["success"] == 1+ # The success path clears both the failure streak and any circuit membership.+ assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=team_id)) is None+ assert fake_redis.zscore(CIRCUIT_ZSET, str(team_id)) is None+++def test_rebuild_exception_is_caught_and_counts_as_failure(fake_redis):+ _enqueue(fake_redis, 5)+ with _rebuilds(error=Exception("db error")):+ stats = drain_rebuild_requests()++ # A raised rebuild must be caught (not abort the whole drain) and counted as a failure+ # that advances the streak.+ assert stats["failure"] == 1+ assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=5)) == b"1"+++def test_batch_load_failure_counts_every_team_as_failure(fake_redis):+ for team_id in (11, 12, 13):+ _enqueue(fake_redis, team_id)+ with _rebuilds(load_error=Exception("db down")):+ stats = drain_rebuild_requests()++ # If the batched DB load raises, the whole batch is recorded as failures (so a+ # persistent outage trips circuits normally instead of silently dropping teams).+ assert stats["failure"] == 3+ for team_id in (11, 12, 13):+ assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=team_id)) == b"1"+++def test_group_mapping_guard_skips_write_without_counting_failure(fake_redis):+ _enqueue(fake_redis, 8)+ with _rebuilds(skip_write=True) as set_cache:+ stats = drain_rebuild_requests()++ # The guard vetoed the write (e.g. personhog lag would empty group_type_mapping):+ # no cache write, and neither success nor failure — so it can't trip the circuit.+ set_cache.assert_not_called()+ assert stats["success"] == 0 and stats["failure"] == 0+ assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=8)) is None+ # Cooldown released so the team retries next drain once the mapping is available.+ assert not fake_redis.exists(COOLDOWN_KEY.format(team_id=8))+++def test_soft_time_limit_propagates_and_is_not_counted_as_failure(fake_redis):+ _enqueue(fake_redis, 3)+ with _rebuilds(error=SoftTimeLimitExceeded()):+ # The soft limit must wind the task down, not be swallowed as a team failure.+ with pytest.raises(SoftTimeLimitExceeded):+ drain_rebuild_requests()++ assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=3)) is None+ # Cooldown released on wind-down so the next drain retries promptly (~1 min).+ assert not fake_redis.exists(COOLDOWN_KEY.format(team_id=3))+++def test_gauges_reflect_queue_and_circuit_state(fake_redis):+ # Oldest pending team enqueued ~3s ago (score is epoch millis); guards the /1000.0+ # ms→s conversion, which every other test leaves untested by enqueuing score=0.+ _enqueue(fake_redis, 42, score=(time.time() - 3.0) * 1000.0)+ # A team with an open (future-scored) circuit feeds the dead-letter gauge.+ fake_redis.zadd(CIRCUIT_ZSET, {"99": time.time() + 3600})++ with _rebuilds():+ drain_rebuild_requests()++ age = REGISTRY.get_sample_value("posthog_flag_definitions_rebuild_oldest_age_seconds")+ dead = REGISTRY.get_sample_value("posthog_flag_definitions_rebuild_dead_letter_teams")+ assert age is not None and 2.0 <= age <= 30.0+ assert dead == 1.0+++def test_request_zset_key_matches_rust_contract():+ # Tripwire for the hand-synced cross-language key: a Python-side rename trips here+ # and prompts updating FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET in the Rust service.+ assert REBUILD_REQUESTS_ZSET == "flag_definitions:rebuild_requests"diff --git a/rust/common/hypercache/src/lib.rs b/rust/common/hypercache/src/lib.rsindex 4cd9a8f3afee..b313a256bba8 100644--- a/rust/common/hypercache/src/lib.rs+++ b/rust/common/hypercache/src/lib.rs@@ -36,7 +36,10 @@ use common_metrics::{histogram, inc};use common_redis::Client as RedisClient;#[cfg(all(test, feature = "mock-client"))]use common_s3::MockS3Client;-use common_s3::{S3Client, S3Error, S3Impl};+use common_s3::S3Impl;+// Re-exported so callers of the public `new_with_s3_client` can name the S3 trait+// (e.g. to inject a test double) without depending on common_s3 directly.+pub use common_s3::{S3Client, S3Error};use common_types::{TeamId, TeamIdentifier};#[cfg(all(test, feature = "mock-client"))]use mockall::predicate;diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rsindex d92d0f5d8acd..4c7e81ba9ead 100644--- a/rust/feature-flags/src/api/flag_definitions.rs+++ b/rust/feature-flags/src/api/flag_definitions.rs@@ -9,6 +9,7 @@ use crate::{metrics::consts::{FLAG_DEFINITIONS_AUTH_COUNTER, FLAG_DEFINITIONS_CACHE_HIT_COUNTER,FLAG_DEFINITIONS_CACHE_MISS_COUNTER, FLAG_DEFINITIONS_ETAG_COUNTER,+ FLAG_DEFINITIONS_REBUILD_REQUESTED_COUNTER,},router::State as AppState,team::team_models::Team,@@ -27,9 +28,17 @@ use serde::{Deserialize, Serialize};use serde_json::Value;use sqlx::PgPool;use std::collections::HashSet;+use std::time::{SystemTime, UNIX_EPOCH};use tracing::{info, warn};const ALLOWLIST_TTL_SECS: u64 = 60;++/// Redis sorted set holding team IDs whose flag-definitions cache is missing and+/// needs a rebuild. A Celery worker drains it (member = team_id, score = enqueue+/// time in epoch millis). Must stay in sync with `REBUILD_REQUESTS_ZSET` in+/// `products/feature_flags/backend/rebuild_queue.py` (pinned by the Python test+/// `test_request_zset_key_matches_rust_contract`).+const FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET: &str = "flag_definitions:rebuild_requests";static CONSTANCE_KEY: Lazy<String> = Lazy::new(|| constance_key("RATE_LIMITING_ALLOW_LIST_TEAMS"));/// Refresh the rate limit allowlist from the database if stale, then update the limiter.@@ -449,11 +458,50 @@ async fn get_from_cache(error = %e,"Flag definitions cache miss");+ // Self-heal: a genuinely empty cache (not a transient redis/s3/parse+ // error) has no DB fallback here, so it would 503 until something+ // rewrites it. Enqueue a debounced rebuild request for a Celery worker.+ if reason == "cache_miss" && *state.config.flag_definitions_self_heal_enabled {+ enqueue_flag_definitions_rebuild(state, team_id);+ }Err(FlagError::from(e))}}}+/// Fire-and-forget enqueue of a flag-definitions rebuild request on cache miss.+///+/// Writes to a Redis sorted set on `state.redis_client` — the same shared client+/// the flags-with-cohorts HyperCacheReader is built from (see `server.rs`), so the+/// queue can never point at a different Redis than the one the cache lives in.+/// Re-enqueuing a team only updates its score, so a client polling a missing team+/// every ~30s occupies a single slot. Spawned so it never adds latency to (or+/// changes) the failing response.+fn enqueue_flag_definitions_rebuild(state: &AppState, team_id: i32) {+ let redis = state.redis_client.clone();+ tokio::spawn(async move {+ let score = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_millis() as i64)+ .unwrap_or(0);+ let result = redis+ .zadd(+ FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET.to_string(),+ team_id.to_string(),+ score,+ )+ .await;+ inc(+ FLAG_DEFINITIONS_REBUILD_REQUESTED_COUNTER,+ &[(+ "result".to_string(),+ if result.is_ok() { "ok" } else { "error" }.to_string(),+ )],+ 1,+ );+ });+}+/// Authenticates flag definitions requests using team secret API tokens or personal API keys////// Validates that the authentication credential has access to the specified team.diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rsindex c999c09925ac..bf566d435f5d 100644--- a/rust/feature-flags/src/config.rs+++ b/rust/feature-flags/src/config.rs@@ -452,6 +452,13 @@ pub struct Config {#[envconfig(default = "false")]pub flags_redis_enabled: FlexBool,+ // Kill-switch for the flag-definitions self-heal path. When enabled, a+ // /flags/definitions cache miss enqueues a (debounced) rebuild request that a+ // Celery worker drains and rebuilds. Default on; set to "false" to instantly+ // stop enqueuing if it ever misbehaves in prod.+ #[envconfig(from = "FLAG_DEFINITIONS_SELF_HEAL_ENABLED", default = "true")]+ pub flag_definitions_self_heal_enabled: FlexBool,+// S3 configuration for HyperCache fallback#[envconfig(default = "posthog")]pub object_storage_bucket: String,@@ -1014,6 +1021,7 @@ impl Config {flags_redis_url: "".to_string(),flags_redis_reader_url: "".to_string(),flags_redis_enabled: FlexBool(false),+ flag_definitions_self_heal_enabled: FlexBool(false),redis_response_timeout_ms: 100,redis_connection_timeout_ms: 5000,write_database_url: "postgres://posthog:posthog@localhost:5432/test_posthog"diff --git a/rust/feature-flags/src/main.rs b/rust/feature-flags/src/main.rsindex 49c02cd623ba..745c407df337 100644--- a/rust/feature-flags/src/main.rs+++ b/rust/feature-flags/src/main.rs@@ -154,7 +154,7 @@ async fn async_main(mut config: Config, rayon_dispatcher: RayonDispatcher) {let listener = tokio::net::TcpListener::bind(config.address).await.expect("could not bind port");- serve(config, listener, rayon_dispatcher, handles).await;+ serve(config, listener, rayon_dispatcher, handles, None).await;// Exit non-zero on dirty shutdown so `restart: on-failure` policies// (hobby docker-compose, default Docker) restart the container.diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex 89e528c057f1..6202fb36873e 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -324,6 +324,11 @@ pub const FLAG_DEFINITIONS_CACHE_MISS_COUNTER: &str = "flags_flag_definitions_ca// Labels: result (hit = 304, miss = 200 with stale etag, none = 200 without etag, redis_error = etag read failed)pub const FLAG_DEFINITIONS_ETAG_COUNTER: &str = "flags_flag_definitions_etag_total";+// Flag definitions self-heal: a cache miss enqueued a rebuild request for a Celery+// worker to drain. Labels: result (ok = enqueued, error = redis zadd failed).+pub const FLAG_DEFINITIONS_REBUILD_REQUESTED_COUNTER: &str =+ "flags_flag_definitions_rebuild_requested_total";+// Flag definitions auth method// Labels: method (secret_api_key, personal_api_key) — Rust only supports these two; Python also tracks oauth, jwt, session, otherpub const FLAG_DEFINITIONS_AUTH_COUNTER: &str = "flags_flag_definitions_auth_total";diff --git a/rust/feature-flags/src/server.rs b/rust/feature-flags/src/server.rsindex 06fcf4a8f0d0..86ae846bf847 100644--- a/rust/feature-flags/src/server.rs+++ b/rust/feature-flags/src/server.rs@@ -19,7 +19,7 @@ use crate::tokio_monitor::TokioRuntimeMonitor;use common_cache::NegativeCache;use common_cookieless::CookielessManager;use common_geoip::GeoIpClient;-use common_hypercache::{HyperCacheConfig, HyperCacheReader};+use common_hypercache::{HyperCacheConfig, HyperCacheReader, S3Client};use common_redis::{Client, CompressionConfig, ReadWriteClient, ReadWriteClientConfig, RedisClient,};@@ -108,6 +108,10 @@ pub async fn serve(listener: TcpListener,rayon_dispatcher: RayonDispatcher,handles: LifecycleHandles,+ // Test-only override for the flags-with-cohorts reader's S3 client. `None` in+ // production; tests inject a dummy so a cache miss classifies as CacheMiss without+ // a real object store. Uses the `new_with_s3_client` testing seam on HyperCacheReader.+ flags_with_cohorts_s3: Option<Arc<dyn S3Client + Send + Sync>>,) {// Configure compression based on environment variablelet compression_config = if *config.redis_compression_enabled {@@ -349,23 +353,31 @@ pub async fn serve(flags_with_cohorts_config.s3_endpoint = Some(config.object_storage_endpoint.clone());}- let flags_with_cohorts_hypercache_reader =- match HyperCacheReader::new(flags_with_cohorts_redis_client, flags_with_cohorts_config)- .await- {- Ok(reader) => {- tracing::info!("Created HyperCacheReader for flags with cohorts");- Arc::new(reader)- }- Err(e) => {- tracing::error!(- "Failed to create flags with cohorts HyperCacheReader: {:?}",- e- );- handles.fail_init(format!("flags with cohorts hypercache init failed: {e:?}"));- return;+ let flags_with_cohorts_hypercache_reader = match flags_with_cohorts_s3 {+ Some(s3) => Arc::new(HyperCacheReader::new_with_s3_client(+ flags_with_cohorts_redis_client,+ s3,+ flags_with_cohorts_config,+ )),+ None => {+ match HyperCacheReader::new(flags_with_cohorts_redis_client, flags_with_cohorts_config)+ .await+ {+ Ok(reader) => {+ tracing::info!("Created HyperCacheReader for flags with cohorts");+ Arc::new(reader)+ }+ Err(e) => {+ tracing::error!(+ "Failed to create flags with cohorts HyperCacheReader: {:?}",+ e+ );+ handles.fail_init(format!("flags with cohorts hypercache init failed: {e:?}"));+ return;+ }}- };+ }+ };// Create HyperCacheReader for remote config (array/config.json)// This reads the pre-computed config blob from Python's RemoteConfig.build_config()diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rsindex e59f95e947e6..efbf583782c6 100644--- a/rust/feature-flags/src/utils/test_utils.rs+++ b/rust/feature-flags/src/utils/test_utils.rs@@ -205,6 +205,55 @@ pub async fn setup_redis_client(url: Option<String>) -> Arc<dyn RedisClientTraitArc::new(client)}+/// Read the members of the flag-definitions self-heal rebuild-requests sorted set.+/// Used by tests asserting the endpoint enqueues (or doesn't) on a cache miss.+pub async fn read_flag_definitions_rebuild_requests(redis_url: &str) -> Vec<String> {+ let redis = setup_redis_client(Some(redis_url.to_string())).await;+ redis+ .zrangebyscore(+ "flag_definitions:rebuild_requests".to_string(),+ "-inf".to_string(),+ "+inf".to_string(),+ )+ .await+ .unwrap_or_default()+}++/// An S3 client that reports every key as NotFound. Lets integration tests force a+/// genuine HyperCache `CacheMiss` (redis miss + S3 NotFound) without a real object+/// store, so a `/flags/definitions` miss classifies as `cache_miss` rather than+/// `s3_error`.+pub struct AlwaysMissS3Client;++#[async_trait]+impl common_hypercache::S3Client for AlwaysMissS3Client {+ async fn get_string(+ &self,+ _bucket: &str,+ key: &str,+ ) -> Result<String, common_hypercache::S3Error> {+ Err(common_hypercache::S3Error::NotFound(key.to_string()))+ }++ async fn put_string(+ &self,+ _bucket: &str,+ _key: &str,+ _value: &str,+ ) -> Result<(), common_hypercache::S3Error> {+ Ok(())+ }++ async fn delete(&self, _bucket: &str, _key: &str) -> Result<(), common_hypercache::S3Error> {+ Ok(())+ }+}++/// A dummy S3 client (always NotFound) for injecting into the test server.+pub fn dummy_s3_client() -> Arc<dyn common_hypercache::S3Client + Send + Sync> {+ Arc::new(AlwaysMissS3Client)+}+/// Create a HyperCacheReader for tests using the provided Redis client./// Uses default test configuration for S3 (which won't be used in most tests/// since Redis should have the data).diff --git a/rust/feature-flags/tests/common/mod.rs b/rust/feature-flags/tests/common/mod.rsindex 12027ef6cb20..d310ed062f5e 100644--- a/rust/feature-flags/tests/common/mod.rs+++ b/rust/feature-flags/tests/common/mod.rs@@ -44,6 +44,17 @@ fn build_test_manager(token: CancellationToken) -> Manager {impl ServerHandle {pub async fn for_config(config: Config) -> ServerHandle {+ Self::for_config_with_s3(config, None).await+ }++ /// Like `for_config`, but injects an S3 client for the flags-with-cohorts reader.+ /// Pass a dummy that returns NotFound to make a cache miss classify as CacheMiss+ /// (the flags Rust test job has no object store, so real S3 reads error out).+ #[allow(dead_code)]+ pub async fn for_config_with_s3(+ config: Config,+ flags_with_cohorts_s3: Option<Arc<dyn common_hypercache::S3Client + Send + Sync>>,+ ) -> ServerHandle {let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();let addr = listener.local_addr().unwrap();let shutdown = CancellationToken::new();@@ -53,7 +64,14 @@ impl ServerHandle {let rayon_dispatcher = RayonDispatcher::new(2, None);tokio::spawn(async move {- serve(config, listener, rayon_dispatcher, handles).await;+ serve(+ config,+ listener,+ rayon_dispatcher,+ handles,+ flags_with_cohorts_s3,+ )+ .await;// Drain the lifecycle monitor after serve returns so the supervisor// thread exits cleanly. Any error is logged — a failing shutdown// shouldn't fail the test unless the test explicitly asserts on it.diff --git a/rust/feature-flags/tests/test_flag_definitions.rs b/rust/feature-flags/tests/test_flag_definitions.rsindex a9bc0ee1e7bf..a68b89c6af1c 100644--- a/rust/feature-flags/tests/test_flag_definitions.rs+++ b/rust/feature-flags/tests/test_flag_definitions.rs@@ -2641,3 +2641,102 @@ async fn test_flag_definitions_billing_counter(#[case] skip_writes: bool) {);}}++/// Poll the self-heal rebuild-requests set until it contains `team_id`, or return+/// false after ~2s. The enqueue runs in a background task, so a bounded retry is+/// needed rather than a single read.+async fn poll_for_rebuild_enqueue(redis_url: &str, team_id: i32) -> bool {+ use feature_flags::utils::test_utils::read_flag_definitions_rebuild_requests;+ use tokio::time::{sleep, Duration};++ for _ in 0..40 {+ let members = read_flag_definitions_rebuild_requests(redis_url).await;+ if members.contains(&team_id.to_string()) {+ return true;+ }+ sleep(Duration::from_millis(50)).await;+ }+ false+}++#[tokio::test]+async fn test_cache_miss_enqueues_rebuild_when_self_heal_enabled() {+ use feature_flags::{+ config::{Config, FlexBool},+ utils::test_utils::{dummy_s3_client, TestContext},+ };+ use reqwest;++ let mut config = Config::default_test_config();+ config.flag_definitions_self_heal_enabled = FlexBool(true);+ let context = TestContext::new(Some(&config)).await;++ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();+ // Don't populate the cache, and inject a NotFound S3 so the read is a genuine+ // cache_miss (the flags test job has no object store, so real S3 would error).+ let server =+ common::ServerHandle::for_config_with_s3(config.clone(), Some(dummy_s3_client())).await;+ let response = reqwest::Client::new()+ .get(format!(+ "http://{}/flags/definitions?token={}",+ server.addr, team.api_token+ ))+ .header("Authorization", format!("Bearer {secret_token}"))+ .send()+ .await+ .unwrap();++ assert_eq!(response.status(), 503, "expected a cache-miss 503");+ assert!(+ poll_for_rebuild_enqueue(&config.redis_url, team.id).await,+ "team {} should be enqueued for rebuild after a cache-miss 503",+ team.id+ );+}++#[tokio::test]+async fn test_cache_miss_does_not_enqueue_rebuild_when_self_heal_disabled() {+ use feature_flags::{+ config::Config,+ utils::test_utils::{dummy_s3_client, read_flag_definitions_rebuild_requests, TestContext},+ };+ use reqwest;+ use tokio::time::{sleep, Duration};++ // default_test_config leaves flag_definitions_self_heal_enabled = false.+ let config = Config::default_test_config();+ let context = TestContext::new(Some(&config)).await;++ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();++ // Inject a NotFound S3 so this is a genuine cache_miss: the only reason no enqueue+ // happens is the flag being off, not the miss classifying as s3_error.+ let server =+ common::ServerHandle::for_config_with_s3(config.clone(), Some(dummy_s3_client())).await;+ let response = reqwest::Client::new()+ .get(format!(+ "http://{}/flags/definitions?token={}",+ server.addr, team.api_token+ ))+ .header("Authorization", format!("Bearer {secret_token}"))+ .send()+ .await+ .unwrap();++ assert_eq!(response.status(), 503, "expected a cache-miss 503");++ // Give any (erroneous) background enqueue time to land, then assert it did not.+ sleep(Duration::from_millis(500)).await;+ let members = read_flag_definitions_rebuild_requests(&config.redis_url).await;+ assert!(+ !members.contains(&team.id.to_string()),+ "team {} must not be enqueued when self-heal is disabled",+ team.id+ );+}