: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): route the hourly cache refresh sweep through Kafka (#101654)
James Gilla3c2491152f6
diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 70ebc562be7f..5c220183836b 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -4,7 +4,7 @@ from contextlib import suppressfrom posthog.settings.access import SECRET_KEYfrom posthog.settings.base_variables import TEST-from posthog.settings.utils import get_from_env, get_list, get_set+from posthog.settings.utils import get_from_env, get_list, get_set, str_to_bool# Used mostly by the hobby install to have some feature flags enabled by default# NOTE: This only affects the frontend, the same FFs will still be considered disabled on the backend@@ -79,6 +79,39 @@ FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS: int = get_from_env(# See cache_expiry_manager.py for implementation details.FLAGS_CACHE_REFRESH_LIMIT: int = get_from_env("FLAGS_CACHE_REFRESH_LIMIT", 5000, type_cast=int)+# Pacing for the teams the refresh sweep routes to the Kafka cache builder instead of+# building itself. The builder drains a batch sequentially, so a whole run produced at+# once sits in front of the flag edits raised after it and delays their rebuilds. The+# run pauses for CHUNK_DELAY_SECONDS after every CHUNK_SIZE routed teams. WINDOW_SECONDS+# caps the total pause, so a misconfigured chunk size or delay cannot make an hourly run+# outlive its schedule.+#+# The window has to stay under the worker pod's termination grace period, currently 1230+# seconds, because the pause happens inside the task and Celery waits for it on shutdown.+# A window at or above that means a deploy landing mid-sweep leaves the pod in Terminating+# for the rest of the run and then kills it before the end-of-run metrics push. 600 covers+# a fully routed run at the volumes the sweep sees today, which peak around 2,300 teams+# and need about 9 pauses. A larger run spends the window and routes the rest unpaced,+# which logs a warning.+# Per-deployment kill switch for routing the refresh sweep to the Kafka builder, read+# before the per-team flag. The flag cannot do this job: local evaluation resolves it+# against the single project key in posthog/apps.py, so raising it raises it in every+# region at once, including one whose flags-cache-builder still rejects the `source`+# field.+FLAGS_CACHE_REFRESH_KAFKA_ENABLED: bool = get_from_env(+ "FLAGS_CACHE_REFRESH_KAFKA_ENABLED", False, type_cast=str_to_bool+)++FLAGS_CACHE_REFRESH_KAFKA_CHUNK_SIZE: int = max(+ 1, get_from_env("FLAGS_CACHE_REFRESH_KAFKA_CHUNK_SIZE", 250, type_cast=int)+)+FLAGS_CACHE_REFRESH_KAFKA_CHUNK_DELAY_SECONDS: float = max(+ 0.0, get_from_env("FLAGS_CACHE_REFRESH_KAFKA_CHUNK_DELAY_SECONDS", 60.0, type_cast=float)+)+FLAGS_CACHE_REFRESH_KAFKA_WINDOW_SECONDS: float = max(+ 0.0, get_from_env("FLAGS_CACHE_REFRESH_KAFKA_WINDOW_SECONDS", 600.0, type_cast=float)+)+# Batch size for flags cache verification. Each batch loads both cached data# (from Redis) and DB data (FeatureFlag objects) into memory simultaneously.# Teams with 100+ flags and large filters JSONs can use significant memory.diff --git a/posthog/storage/cache_expiry_manager.py b/posthog/storage/cache_expiry_manager.pyindex 328fc09d40f1..d530ee794ae3 100644--- a/posthog/storage/cache_expiry_manager.py+++ b/posthog/storage/cache_expiry_manager.py@@ -8,6 +8,7 @@ across different HyperCache types (flags, team metadata, etc.).from __future__ import annotationsimport time+from typing import Literalimport structlog@@ -19,6 +20,8 @@ from posthog.storage.hypercache_manager import HyperCacheManagementConfig, push_logger = structlog.get_logger(__name__)+RefreshOutcome = Literal["successful", "failed", "enqueued"]+def get_teams_with_expiring_caches(config: HyperCacheManagementConfig, ttl_threshold_hours: int = 24, limit: int = 5000@@ -47,7 +50,7 @@ def get_teams_with_expiring_caches(redis_client = get_client(hypercache.redis_url)# Query sorted set for teams expiring within threshold- threshold_timestamp = time.time() + (ttl_threshold_hours * 3600)+ threshold_timestamp = _expiry_threshold(ttl_threshold_hours)# Get identifiers of teams expiring before threshold (score is expiration timestamp)expiring_identifiers = redis_client.zrangebyscore(@@ -86,72 +89,215 @@ def get_teams_with_expiring_caches(return []+def count_expiring_caches(config: HyperCacheManagementConfig, ttl_threshold_hours: int = 24) -> int | None:+ """+ Count the entries due for refresh in the expiry tracking sorted set.++ Deliberately unbounded, unlike get_teams_with_expiring_caches, which stops at the+ run's limit. The count is the sweep's saturation signal: it has to be able to+ exceed what one run processes, or it cannot tell a drained queue from a queue the+ sweep is falling behind on.++ Args:+ config: HyperCache management config specifying which cache to count+ ttl_threshold_hours: Count entries expiring within this many hours++ Returns:+ Number of entries due for refresh, or None if the count is unavailable+ """+ hypercache = config.hypercache++ if not hypercache.expiry_sorted_set_key:+ return None++ try:+ redis_client = get_client(hypercache.redis_url)+ return redis_client.zcount(hypercache.expiry_sorted_set_key, "-inf", _expiry_threshold(ttl_threshold_hours))+ except Exception as e:+ logger.warning(f"Error counting expiring {config.log_prefix}", error=str(e))+ return None+++def _expiry_threshold(ttl_threshold_hours: int) -> float:+ """The sorted-set score below which an entry is due for refresh. Shared so the+ backlog gauge always describes the same set the sweep pulls its teams from."""+ return time.time() + (ttl_threshold_hours * 3600)++@frozenclass CacheRefreshCounts:successful: intfailed: int+ enqueued: int = 0+++@frozen+class RefreshPacing:+ """+ How fast a run may hand teams to `config.route_refresh_fn`.++ Only routed teams are paced. A team the sweep builds itself already takes tens of+ milliseconds, while routing is a message produce, so an unpaced run delivers its+ whole batch in one burst. The receiving builder drains sequentially, so that burst+ sits in front of every message raised after it and delays the work those messages+ stand for.++ Passed per run rather than held on the config, so the values can come from settings+ at call time. The config is built at module import, which would freeze them.++ `window_seconds` bounds the total pause, and it is a wall-clock bound for a reason:+ the pause is a `time.sleep` inside the Celery task, so it holds the worker process+ and its database connection, and Celery waits for it on shutdown. Keep the window+ under the worker pod's termination grace period, or a deploy landing mid-run holds+ the pod in Terminating and then kills it before the run pushes its metrics. That is+ also why the window is not expressed as a number of pauses: a pause count stops+ bounding wall-clock the moment someone raises `delay_seconds`.+ """++ chunk_size: int+ delay_seconds: float+ window_seconds: float++ def __post_init__(self) -> None:+ # The loop reads `routed_since_pause < chunk_size`, so a chunk below 1 pauses+ # after every team instead of never. Callers clamp their own settings, but the+ # invariant belongs to the type: the next caller writes its own settings.+ if self.chunk_size < 1:+ raise ValueError(f"chunk_size must be at least 1, got {self.chunk_size}")+ if self.delay_seconds < 0 or self.window_seconds < 0:+ raise ValueError("pacing delays must not be negative")+++def push_refresh_metrics(+ config: HyperCacheManagementConfig, counts: CacheRefreshCounts, ttl_threshold_hours: int = 24+) -> None:+ """+ Push a refresh run's counts and its expiry backlog to Pushgateway.++ Every sweep over the expiry sorted set ends here, including the batch-loading fork+ in remote_config_cache. One function so the next field added reaches both without+ anyone having to remember the fork exists.++ An empty run pushes too. Pushgateway keeps serving the last value pushed, so+ skipping it would latch a drained backlog at whatever the last busy run saw.+ """+ push_hypercache_teams_processed_metrics(+ namespace=config.namespace,+ cache_name=config.cache_name,+ successful=counts.successful,+ failed=counts.failed,+ enqueued=counts.enqueued,+ expiry_backlog=count_expiring_caches(config, ttl_threshold_hours),+ )def refresh_expiring_caches(- config: HyperCacheManagementConfig, ttl_threshold_hours: int = 24, limit: int = 5000+ config: HyperCacheManagementConfig,+ ttl_threshold_hours: int = 24,+ limit: int = 5000,+ pacing: RefreshPacing | None = None,) -> CacheRefreshCounts:"""Refresh caches that are expiring soon to prevent cache misses.This is the main hourly job that keeps caches fresh. It:1. Finds teams whose caches are expiring within the threshold (up to limit)- 2. Refreshes each cache by calling the configured update function- 3. Returns success/failure counts+ 2. Refreshes each cache, either by calling the configured update function or, when+ the config binds a routing hook that claims the team, by handing the refresh to+ the builder behind that hook+ 3. Returns successful/failed/enqueued counts, which sum to the number of teams the+ run processed++ A routed team is counted as enqueued and never as successful. Its build happens+ elsewhere and after this run ends, so counting it as successful would report a+ healthy sweep while the other builder was down.Args:config: HyperCache management config specifying which cache to refreshttl_threshold_hours: Refresh caches expiring within this many hourslimit: Maximum number of teams to refresh per run (default 5000)+ pacing: Optional pacing for routed teams. Ignored when no team is routed.Returns:- CacheRefreshCounts with successful and failed counts+ CacheRefreshCounts with successful, failed and enqueued counts"""teams = get_teams_with_expiring_caches(config, ttl_threshold_hours, limit)+ counts = _refresh_teams(config, teams, pacing)++ logger.info(+ f"Completed refreshing {config.log_prefix}",+ successful=counts.successful,+ failed=counts.failed,+ enqueued=counts.enqueued,+ total=len(teams),+ )++ push_refresh_metrics(config, counts, ttl_threshold_hours)- if not teams:- logger.info(f"No {config.log_prefix} to refresh")- return CacheRefreshCounts(successful=0, failed=0)+ return counts++def _refresh_teams(+ config: HyperCacheManagementConfig, teams: list[Team], pacing: RefreshPacing | None+) -> CacheRefreshCounts:successful = 0failed = 0-- for team in teams:- try:- success = config.update_fn(team)- if success:- successful += 1- else:- failed += 1- except Exception as e:- logger.exception(- f"Failed to refresh {config.log_prefix[:-1]}",- team_id=team.id,- error=str(e),- )- capture_exception(e)+ enqueued = 0+ routed_since_pause = 0+ slept_seconds = 0.0+ window_exhausted = False+ last_index = len(teams) - 1++ for index, team in enumerate(teams):+ outcome = _refresh_one_team(config, team)+ if outcome == "enqueued":+ enqueued += 1+ elif outcome == "successful":+ successful += 1+ else:failed += 1- logger.info(- f"Completed refreshing {config.log_prefix}",- successful=successful,- failed=failed,- total=len(teams),- )+ if outcome != "enqueued" or pacing is None or index == last_index:+ continue- # Push metrics to Pushgateway (Gauges work better than Counters for batch jobs)- push_hypercache_teams_processed_metrics(- namespace=config.namespace,- cache_name=config.cache_name,- successful=successful,- failed=failed,- )+ routed_since_pause += 1+ if routed_since_pause < pacing.chunk_size:+ continue++ routed_since_pause = 0+ remaining_window = pacing.window_seconds - slept_seconds+ if remaining_window <= 0:+ # Routing the rest unpaced is worse for the receiving builder than pacing,+ # and better than a run that overlaps the next one.+ if not window_exhausted:+ window_exhausted = True+ logger.warning(+ f"Pacing window spent while refreshing {config.log_prefix}, routing the rest unpaced",+ window_seconds=pacing.window_seconds,+ teams_routed=enqueued,+ )+ continue- return CacheRefreshCounts(successful=successful, failed=failed)+ delay = min(pacing.delay_seconds, remaining_window)+ time.sleep(delay)+ slept_seconds += delay++ return CacheRefreshCounts(successful=successful, failed=failed, enqueued=enqueued)+++def _refresh_one_team(config: HyperCacheManagementConfig, team: Team) -> RefreshOutcome:+ try:+ if config.route_refresh_fn is not None and config.route_refresh_fn(team.id):+ return "enqueued"+ return "successful" if config.update_fn(team) else "failed"+ except Exception as e:+ logger.exception(+ f"Failed to refresh {config.log_prefix[:-1]}",+ team_id=team.id,+ error=str(e),+ )+ capture_exception(e)+ return "failed"def cleanup_stale_expiry_tracking(config: HyperCacheManagementConfig) -> int:diff --git a/posthog/storage/hypercache_manager.py b/posthog/storage/hypercache_manager.pyindex b20e1812e058..350ad7bbe934 100644--- a/posthog/storage/hypercache_manager.py+++ b/posthog/storage/hypercache_manager.py@@ -126,6 +126,8 @@ def push_hypercache_teams_processed_metrics(cache_name: str,successful: int,failed: int,+ enqueued: int = 0,+ expiry_backlog: int | None = None,) -> None:"""Push teams processed metrics to Pushgateway after batch refresh operations.@@ -142,6 +144,13 @@ def push_hypercache_teams_processed_metrics(cache_name: The canonical cache name (e.g., "team_metadata", "llm_gateway_policy")successful: Number of teams successfully processedfailed: Number of teams that failed processing+ enqueued: Number of teams whose refresh was routed to another builder instead+ of being built in this process. Kept apart from `successful` because the+ build has not happened yet when the run ends, so folding the two together+ would report a healthy sweep while the other builder was down.+ expiry_backlog: Entries in the expiry sorted set that are due for refresh,+ sampled after the run. None when the count is unavailable, which pushes+ no series rather than a zero that reads as a drained queue."""if not settings.PROM_PUSHGATEWAY_ADDRESS:return@@ -156,6 +165,16 @@ def push_hypercache_teams_processed_metrics()success_gauge.labels(namespace=namespace, cache_name=cache_name, result="success").set(successful)success_gauge.labels(namespace=namespace, cache_name=cache_name, result="failure").set(failed)+ success_gauge.labels(namespace=namespace, cache_name=cache_name, result="enqueued").set(enqueued)++ if expiry_backlog is not None:+ backlog_gauge = Gauge(+ "posthog_hypercache_expiry_backlog_last_run",+ "Entries due for refresh in the expiry sorted set, sampled after the last batch refresh run",+ labelnames=["namespace", "cache_name"],+ registry=registry,+ )+ backlog_gauge.labels(namespace=namespace, cache_name=cache_name).set(expiry_backlog)except Exception as e:logger.warning("Failed to push hypercache teams processed to Pushgateway",@@ -225,6 +244,19 @@ class HyperCacheManagementConfig:# veto is neither a fix nor a failure. `update_fn` paths already guard internally.should_skip_write: Callable[[Any, dict], bool] | None = None+ # Optional routing hook for the expiry refresh sweep, called per team before the+ # sweep would call update_fn. True hands the refresh to another builder, which+ # makes the sweep skip its own build and count the team as enqueued. Unset, the+ # sweep only ever builds, which is what every cache that has not opted in gets.+ # The hook owns its own gating, so a cache can ramp the handover per team. A hook+ # that raises makes the sweep count the team as failed and skip the build, so it+ # should swallow a gate failure it can decide around, and raise only where failed+ # is the reading it wants.+ # Takes a team id rather than a Team: `refresh_only_fields` defers most columns on+ # the Team the sweep loads, so a hook reading any other field would trigger a lazy+ # refetch, or fail outright against a read replica that has not applied the column.+ route_refresh_fn: Callable[[int], bool] | None = None+# Optional attribution of a team's primary cache writer, used to label verifier# fixes. During a dual-writer migration (Python Celery builder vs Rust Kafka# builder) the verifier is the parity oracle: a fix on a team owned by one writerdiff --git a/posthog/storage/remote_config_cache.py b/posthog/storage/remote_config_cache.pyindex 064ec87bb89a..2e24f765d14a 100644--- a/posthog/storage/remote_config_cache.py+++ b/posthog/storage/remote_config_cache.py@@ -24,11 +24,11 @@ from posthog.storage.cache_expiry_manager import (CacheRefreshCounts,cleanup_stale_expiry_tracking as cleanup_generic,get_teams_with_expiring_caches as get_teams_generic,+ push_refresh_metrics,)from posthog.storage.hypercache_manager import (HyperCacheManagementConfig,get_cache_stats as get_cache_stats_generic,- push_hypercache_teams_processed_metrics,)logger = structlog.get_logger(__name__)@@ -92,9 +92,9 @@ def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) ->table from Team, so re-stamping per team would be an N+1."""teams = get_teams_generic(REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours, limit)- if not teams:- return CacheRefreshCounts(successful=0, failed=0)-+ # An empty run falls through to push_refresh_metrics rather than returning early,+ # for the reason that function gives. Django resolves `team__in=[]` without a+ # query, so the fall-through costs an empty run nothing.team_by_id = {team.id: team for team in teams}configs = dict(RemoteConfig.objects.filter(team__in=teams).values_list("team_id", "config"))@@ -114,13 +114,9 @@ def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) ->capture_exception(e)failed += 1- push_hypercache_teams_processed_metrics(- namespace=REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG.namespace,- cache_name=REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG.cache_name,- successful=successful,- failed=failed,- )- return CacheRefreshCounts(successful=successful, failed=failed)+ counts = CacheRefreshCounts(successful=successful, failed=failed)+ push_refresh_metrics(REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG, counts, ttl_threshold_hours)+ return countsdef cleanup_stale_expiry_tracking() -> int:diff --git a/posthog/storage/test/test_cache_expiry_manager.py b/posthog/storage/test/test_cache_expiry_manager.pynew file mode 100644index 000000000000..2b23b5006fbe--- /dev/null+++ b/posthog/storage/test/test_cache_expiry_manager.py@@ -0,0 +1,157 @@+import time++from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models.team.team import Team+from posthog.storage.cache_expiry_manager import RefreshPacing, refresh_expiring_caches+from posthog.storage.test.test_hypercache_manager import create_test_config as build_config++MODULE = "posthog.storage.cache_expiry_manager"+++def build_teams(count: int) -> list[Team]:+ return [Team(id=team_id) for team_id in range(1, count + 1)]+++class TestRefreshExpiringCaches(SimpleTestCase):+ def setUp(self):+ super().setUp()+ self.teams = build_teams(3)++ teams_patcher = patch(f"{MODULE}.get_teams_with_expiring_caches", return_value=self.teams)+ self.mock_get_teams = teams_patcher.start()+ self.addCleanup(teams_patcher.stop)++ redis_patcher = patch(f"{MODULE}.get_client")+ self.mock_get_client = redis_patcher.start()+ self.addCleanup(redis_patcher.stop)+ self.mock_get_client.return_value.zcount.return_value = 0++ push_patcher = patch(f"{MODULE}.push_hypercache_teams_processed_metrics")+ self.mock_push = push_patcher.start()+ self.addCleanup(push_patcher.stop)++ # Patch the module's `time`, not `time.sleep` on the stdlib module object:+ # `cache_expiry_manager` does `import time`, so patching the attribute reaches+ # every other importer for the duration of the test. The real clock is kept,+ # because the backlog threshold is computed from `time.time()`.+ time_patcher = patch(f"{MODULE}.time")+ mock_time = time_patcher.start()+ mock_time.time.side_effect = time.time+ self.mock_sleep = mock_time.sleep+ self.addCleanup(time_patcher.stop)++ def test_without_a_routing_hook_every_team_is_built(self):+ update_fn = MagicMock(return_value=True)++ counts = refresh_expiring_caches(build_config(update_fn=update_fn))++ assert update_fn.call_count == 3+ assert (counts.successful, counts.failed, counts.enqueued) == (3, 0, 0)++ def test_a_hook_that_declines_a_team_leaves_the_build_to_the_update_fn(self):+ update_fn = MagicMock(return_value=True)+ route_refresh_fn = MagicMock(return_value=False)++ counts = refresh_expiring_caches(build_config(update_fn=update_fn, route_refresh_fn=route_refresh_fn))++ assert route_refresh_fn.call_count == 3+ assert update_fn.call_count == 3+ assert (counts.successful, counts.failed, counts.enqueued) == (3, 0, 0)++ def test_a_routed_team_is_not_built_and_is_counted_as_enqueued(self):+ update_fn = MagicMock(return_value=True)++ counts = refresh_expiring_caches(+ build_config(update_fn=update_fn, route_refresh_fn=MagicMock(return_value=True))+ )++ update_fn.assert_not_called()+ assert (counts.successful, counts.failed, counts.enqueued) == (0, 0, 3)++ def test_the_three_counts_sum_to_the_teams_the_run_processed(self):+ self.mock_get_teams.return_value = build_teams(4)+ # Team 1 routed, team 2 built, team 3 reported as a failed build, team 4 raised.+ route_refresh_fn = MagicMock(side_effect=[True, False, False, False])+ update_fn = MagicMock(side_effect=[True, False, RuntimeError("redis down")])++ counts = refresh_expiring_caches(build_config(update_fn=update_fn, route_refresh_fn=route_refresh_fn))++ assert (counts.successful, counts.failed, counts.enqueued) == (1, 2, 1)+ assert counts.successful + counts.failed + counts.enqueued == 4++ def test_a_hook_that_raises_counts_as_failed_and_does_not_build(self):+ update_fn = MagicMock(return_value=True)+ route_refresh_fn = MagicMock(side_effect=RuntimeError("flag client down"))++ counts = refresh_expiring_caches(build_config(update_fn=update_fn, route_refresh_fn=route_refresh_fn))++ update_fn.assert_not_called()+ assert (counts.successful, counts.failed, counts.enqueued) == (0, 3, 0)++ @parameterized.expand(+ [+ # The ninth team completes a chunk but is last, so nothing waits behind it.+ # A team count that is not a multiple of the chunk never reaches that branch.+ ("all_routed", [True] * 9, 3, [5, 5]),+ # A partial ramp is the run this will actually make, and it is the only one+ # that separates "every third routed team" from "every third team": the+ # built teams must not advance the chunk counter.+ ("half_routed", [True, False, True, False, True, False], 2, [5]),+ ("none_routed", [False] * 3, 1, []),+ ]+ )+ def test_pacing_pauses_once_per_chunk_of_routed_teams(self, _name, routed, chunk_size, expected_delays):+ self.mock_get_teams.return_value = build_teams(len(routed))++ refresh_expiring_caches(+ build_config(route_refresh_fn=MagicMock(side_effect=routed)),+ pacing=RefreshPacing(chunk_size=chunk_size, delay_seconds=5, window_seconds=600),+ )++ assert [call.args[0] for call in self.mock_sleep.call_args_list] == expected_delays++ def test_pacing_stops_once_the_window_is_spent(self):+ self.mock_get_teams.return_value = build_teams(5)++ refresh_expiring_caches(+ build_config(route_refresh_fn=MagicMock(return_value=True)),+ pacing=RefreshPacing(chunk_size=1, delay_seconds=6, window_seconds=10),+ )++ # The second pause is trimmed to what the window has left, and nothing waits after.+ assert [call.args[0] for call in self.mock_sleep.call_args_list] == [6, 4]++ def test_the_backlog_gauge_is_not_capped_by_the_run_limit(self):+ self.mock_get_client.return_value.zcount.return_value = 9000++ refresh_expiring_caches(build_config(), limit=3)++ assert self.mock_push.call_args.kwargs["expiry_backlog"] == 9000+ # Counting a different key or a capped range would still satisfy the value+ # assertion above, so pin which set the gauge reads.+ assert self.mock_get_client.return_value.zcount.call_args.args[0] == "test_cache_expiry"+ assert self.mock_get_client.return_value.zcount.call_args.args[1] == "-inf"++ def test_an_empty_run_still_reports_its_counts_and_backlog(self):+ self.mock_get_teams.return_value = []+ self.mock_get_client.return_value.zcount.return_value = 0++ refresh_expiring_caches(build_config())++ push_kwargs = self.mock_push.call_args.kwargs+ assert push_kwargs["successful"] == 0+ assert push_kwargs["failed"] == 0+ assert push_kwargs["enqueued"] == 0+ assert push_kwargs["expiry_backlog"] == 0++ def test_an_unreadable_backlog_pushes_no_backlog_value(self):+ self.mock_get_client.side_effect = RuntimeError("redis unreachable")++ refresh_expiring_caches(build_config())++ assert self.mock_push.call_args.kwargs["expiry_backlog"] is Nonediff --git a/posthog/storage/test/test_hypercache_manager.py b/posthog/storage/test/test_hypercache_manager.pyindex 39b75d98f880..a0534c22521f 100644--- a/posthog/storage/test/test_hypercache_manager.py+++ b/posthog/storage/test/test_hypercache_manager.py@@ -47,12 +47,16 @@ def create_test_config(namespace: str = "test_namespace",value: str = "test_value",token_based: bool = False,+ update_fn=None,+ route_refresh_fn=None,) -> HyperCacheManagementConfig:"""Create a test HyperCacheManagementConfig with minimal setup."""- def update_fn(team, ttl=None):+ def default_update_fn(team, ttl=None):return True+ update_fn = update_fn or default_update_fn+hypercache = create_test_hypercache(namespace=namespace,value=value,@@ -63,6 +67,7 @@ def create_test_config(hypercache=hypercache,update_fn=update_fn,cache_name="test_cache",+ route_refresh_fn=route_refresh_fn,)@@ -470,6 +475,8 @@ class TestPushHypercacheTeamsProcessedMetrics(BaseTest):cache_name="flags",successful=900,failed=100,+ enqueued=25,+ expiry_backlog=7000,)mock_registry_cm.assert_called_once_with("hypercache_teams_processed_feature_flags_flags")@@ -482,6 +489,37 @@ class TestPushHypercacheTeamsProcessedMetrics(BaseTest):registry.get_sample_value("posthog_hypercache_teams_processed_last_run", {**base, "result": "failure"})== 100)+ assert (+ registry.get_sample_value("posthog_hypercache_teams_processed_last_run", {**base, "result": "enqueued"})+ == 25+ )+ # Once the sweep only produces, this gauge is the only thing left that says+ # whether the queue drains.+ assert registry.get_sample_value("posthog_hypercache_expiry_backlog_last_run", base) == 7000++ @patch("posthog.storage.hypercache_manager.pushed_metrics_registry")+ def test_an_unavailable_backlog_emits_no_backlog_series(self, mock_registry_cm):+ registry = CollectorRegistry()+ mock_registry_cm.return_value.__enter__ = MagicMock(return_value=registry)+ mock_registry_cm.return_value.__exit__ = MagicMock(return_value=False)++ with self.settings(PROM_PUSHGATEWAY_ADDRESS="http://pushgateway:9091"):+ push_hypercache_teams_processed_metrics(+ namespace="feature_flags",+ cache_name="flags",+ successful=900,+ failed=100,+ expiry_backlog=None,+ )++ base = {"namespace": "feature_flags", "cache_name": "flags"}+ # Absent rather than zero: a zero here reads as a drained queue, which is the+ # opposite of "Redis did not answer".+ assert registry.get_sample_value("posthog_hypercache_expiry_backlog_last_run", base) is None+ assert (+ registry.get_sample_value("posthog_hypercache_teams_processed_last_run", {**base, "result": "success"})+ == 900+ )@patch("posthog.storage.hypercache_manager.pushed_metrics_registry")def test_skips_push_when_no_pushgateway_address(self, mock_registry_cm):diff --git a/posthog/storage/test/test_remote_config_cache.py b/posthog/storage/test/test_remote_config_cache.pyindex e722e91711aa..a7ff3c97f6d4 100644--- a/posthog/storage/test/test_remote_config_cache.py+++ b/posthog/storage/test/test_remote_config_cache.py@@ -79,14 +79,25 @@ class TestRefreshExpiringRemoteConfigCaches(BaseTest):_, kwargs = mock_hypercache.set_cache_value_redis_only.call_argsassert kwargs["track_expiry"] is True+ # Patched at the Pushgateway seam rather than at push_refresh_metrics, so the+ # shared helper still runs and the backlog it counts is what gets asserted.+ @patch("posthog.storage.cache_expiry_manager.push_hypercache_teams_processed_metrics")@patch("posthog.storage.cache_expiry_manager.get_client")- def test_returns_zero_when_nothing_expiring(self, mock_get_client):+ def test_an_empty_run_still_reports_its_counts_and_backlog(self, mock_get_client, mock_push):mock_redis = MagicMock()mock_get_client.return_value = mock_redismock_redis.zrangebyscore.return_value = []+ mock_redis.zcount.return_value = 0assert refresh_expiring_caches(ttl_threshold_hours=24) == CacheRefreshCounts(successful=0, failed=0)+ # Pushgateway keeps serving the last value pushed, so a run that returned before+ # pushing would leave a drained backlog reading as the last busy run's count.+ push_kwargs = mock_push.call_args.kwargs+ assert push_kwargs["successful"] == 0+ assert push_kwargs["failed"] == 0+ assert push_kwargs["expiry_backlog"] == 0+class TestCleanupStaleRemoteConfigExpiryTracking(BaseTest):@patch("posthog.storage.cache_expiry_manager.get_client")diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 8f36091a189e..09ed364c472e 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -28,7 +28,7 @@ Manual operations:from collections import defaultdictfrom datetime import UTC, datetime, timedelta-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Literalif TYPE_CHECKING:from django.db.models import QuerySet@@ -53,6 +53,7 @@ from posthog.models.team import Teamfrom posthog.ph_client import feature_enabled_or_falsefrom posthog.storage.cache_expiry_manager import (CacheRefreshCounts,+ RefreshPacing,cleanup_stale_expiry_tracking as cleanup_generic,get_teams_with_expiring_caches,refresh_expiring_caches,@@ -921,6 +922,8 @@ FLAGS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(# Kafka-routing block further down this module and is deleted with it at# cutover, so it isn't defined yet when this config is constructed.get_primary_writer_fn=lambda team_id: get_team_primary_flags_writer(team_id),+ # Late-bound for the same reason as get_primary_writer_fn above.+ route_refresh_fn=lambda team_id: route_refresh_to_kafka(team_id),# The refresh loads flags by team id/project_id; it reads no other Team columns.# Narrowing the SELECT keeps it resilient to newly added Team columns the read# replica may not have applied yet (organization_id keeps the select_related valid).@@ -967,7 +970,9 @@ def refresh_expiring_flags_caches(ttl_threshold_hours: int = 24, limit: int = 50This is the main hourly job that keeps caches fresh. It:1. Finds cache entries with TTL < threshold (up to limit)- 2. Refreshes them with new data and full TTL+ 2. Refreshes them with new data and full TTL, or, for a team the refresh routing+ flag has claimed, raises a Kafka invalidation and leaves the build to the Rust+ builder insteadProcesses teams in batches (default 5000). If more teams are expiring than the limit,subsequent runs will process the next batch.@@ -983,9 +988,18 @@ def refresh_expiring_flags_caches(ttl_threshold_hours: int = 24, limit: int = 50- Responsiveness: Completes quickly enough to not block other operationsReturns:- CacheRefreshCounts with successful and failed refresh counts+ CacheRefreshCounts with successful, failed and enqueued refresh counts"""- return refresh_expiring_caches(FLAGS_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours, limit)+ return refresh_expiring_caches(+ FLAGS_HYPERCACHE_MANAGEMENT_CONFIG,+ ttl_threshold_hours,+ limit,+ pacing=RefreshPacing(+ chunk_size=settings.FLAGS_CACHE_REFRESH_KAFKA_CHUNK_SIZE,+ delay_seconds=settings.FLAGS_CACHE_REFRESH_KAFKA_CHUNK_DELAY_SECONDS,+ window_seconds=settings.FLAGS_CACHE_REFRESH_KAFKA_WINDOW_SECONDS,+ ),+ )def cleanup_stale_expiry_tracking() -> int:@@ -1032,12 +1046,18 @@ def get_cache_stats() -> dict[str, Any]:## Transitional surface: KAFKA_ROUTING_FLAG, _evaluate_kafka_routing_flag,# _route_to_kafka, get_team_primary_flags_writer (and its config binding on-# FLAGS_HYPERCACHE_MANAGEMENT_CONFIG), SHADOW_COMPARE_FLAG, _shadow_compare_enabled,-# publish_shadow_invalidation, _produce_invalidation, _enqueue_invalidation,-# and the Kafka branch inside it.+# FLAGS_HYPERCACHE_MANAGEMENT_CONFIG), REFRESH_ROUTING_FLAG, _refresh_routing_enabled,+# route_refresh_to_kafka (and its config binding), SHADOW_COMPARE_FLAG,+# _shadow_compare_enabled, publish_shadow_invalidation, _produce_invalidation,+# _enqueue_invalidation, and the Kafka branch inside it.# The signal handlers themselves stay; their tails simplify at cutover. The one# call site outside this block is the tail of update_team_service_flags_cache in# tasks.py, which goes with it.+#+# At cutover the sweep routes unconditionally: REFRESH_ROUTING_FLAG and its gate go,+# and the binding is replaced by a hook that always produces, not deleted. The generic+# surface it uses — route_refresh_fn, the enqueued count and RefreshPacing — keeps its+# caller and stays.# Per-team gate that routes invalidation to Kafka instead of Celery — see# _enqueue_invalidation for why the two paths are mutually exclusive. The key@@ -1133,6 +1153,92 @@ def _route_to_kafka(team_id: int) -> bool:return bool(result)+# Per-team gate for the hourly expiry refresh sweep. A different flag from+# KAFKA_ROUTING_FLAG on purpose: that one is pinned at 100% for the edit path, so+# reusing it would move the sweep the moment this code shipped. The two ramp+# independently, and setting this one back to 0 returns the next hourly run to the+# Python builder with no cleanup, because a refresh message already in flight still+# produces a correct build.+REFRESH_ROUTING_FLAG = "flags-cache-refresh-kafka"+++def _refresh_routing_enabled(team_id: int) -> bool:+ """Return True if this team's hourly refresh should be raised as a Kafka+ invalidation instead of being built in the Celery worker.++ FLAGS_CACHE_REFRESH_KAFKA_ENABLED is read before the flag, because the flag cannot+ be scoped to one deployment: local evaluation resolves it against the single+ project key set in posthog/apps.py, so raising it raises it in every region at+ once. A region whose flags-cache-builder image predates the `source` field rejects+ the message through deny_unknown_fields, counts it as a parse error and drops it,+ and the dead letter queue holds build failures rather than parse failures, so+ nothing can be replayed. The setting is read per deployment, so a lagging region+ holds routing off on its own until its builder is rolled.++ Every failure mode returns False, which keeps the sweep building in Python. That+ is the safe direction: a build that happens is never worse than a message nobody+ consumes.++ Unlike `_route_to_kafka`, an unresolvable flag ticks no TOMBSTONE_COUNTER, for the+ reason `_shadow_compare_enabled` gives. Local evaluation cannot resolve+ REFRESH_ROUTING_FLAG for as long as the flag does not exist in PostHog, so a tick+ would fire for every team of every run, which is about 5,000 an hour, and hold a+ constant high rate on a panel that means "rare anomaly". A client that is actually+ broken raises instead, and the warning below records that.+ """+ if not settings.FLAGS_CACHE_REFRESH_KAFKA_ENABLED:+ return False++ try:+ return feature_enabled_or_false(+ REFRESH_ROUTING_FLAG,+ f"team-{team_id}",+ groups={"project": str(team_id)},+ group_properties={"project": {"id": str(team_id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ except Exception:+ # Log so a fleet-wide silent disable is visible in Sentry rather than only as+ # an enqueued gauge that quietly returns to zero mid-ramp.+ logger.warning(+ "flags_cache_refresh_routing_flag_evaluation_failed",+ team_id=team_id,+ flag=REFRESH_ROUTING_FLAG,+ exc_info=True,+ )+ return False+++def route_refresh_to_kafka(team_id: int) -> bool:+ """Routing hook for the expiry refresh sweep, bound on+ FLAGS_HYPERCACHE_MANAGEMENT_CONFIG.++ Returns True when the team's refresh was raised as a Kafka invalidation, which+ makes the sweep skip its own build and count the team as enqueued.++ A produce failure propagates instead of returning True, so the sweep counts the+ team as failed rather than enqueued. That covers what `produce` reports+ synchronously: a full local queue, a serialization error, and a producer that+ cannot be constructed. It does not cover broker-side loss, because `flush_timeout=0`+ returns before any ack, so an unreachable cluster still queues the message locally+ and the team reads as enqueued. The expiry backlog gauge and the verifier are what+ catch that class, never this count.++ A propagated error is still not a Celery fallback, for the reason+ `_enqueue_invalidation` gives: the two paths are mutually exclusive so a broken+ Kafka path shows up as a stale cache instead of being masked by Python quietly+ building the team anyway. The sweep skips its own build for a team whose hook+ failed. A team whose message is lost stays inside the expiry window, so the next+ hourly run raises it again, and the verifier repairs it in the meantime.+ """+ if not _refresh_routing_enabled(team_id):+ return False++ _produce_invalidation(team_id, source="refresh", raise_on_error=True)+ return True++# Per-team gate for shadow parity publishing. A different flag from# KAFKA_ROUTING_FLAG on purpose: this one never decides which writer serves a# team, so the two ramp independently. See flags_cache_messages for what the@@ -1224,8 +1330,14 @@ def publish_shadow_invalidation(team_id: int) -> None:_produce_invalidation(team_id, shadow=True)-def _produce_invalidation(team_id: int, shadow: bool = False) -> None:- """Produce a single invalidation message; swallow Kafka errors.+def _produce_invalidation(+ team_id: int,+ shadow: bool = False,+ source: Literal["edit", "refresh"] = "edit",+ raise_on_error: bool = False,+) -> None:+ """Produce a single invalidation message; log Kafka errors, and propagate them+ only for a caller that reports them.A produce failure must not raise out of a signal handler and is deliberatelynot retried via Celery (see `_enqueue_invalidation`). The `except` below only@@ -1238,9 +1350,21 @@ def _produce_invalidation(team_id: int, shadow: bool = False) -> None:`data` must be a dict, not pre-encoded bytes: `produce` runs it through`json.dumps`, so bytes would `TypeError` and silently fail the swallow path.`mode="json"` converts `datetime` to ISO string.++ `source` names the producer that raised the message. The builder treats every+ source identically and uses the value to attribute builds and latency, so a wrong+ value costs a reading and never a build. See flags_cache_messages for why a region+ whose builder predates the field must not be sent anything but the default.++ `raise_on_error` belongs to the caller, not to the wire: it says whether a caller+ is there to report the failure. The refresh sweep sets it so a team the `except`+ below catches counts as failed instead of as a hand-off that never happened. It+ reaches only that synchronous class, never a delivery failure, which arrives after+ this function has returned. Signal handlers leave it off, because a flag edit has+ nothing to report a produce failure to."""try:- msg = FlagsCacheInvalidation(team_id=team_id, emitted_at=datetime.now(UTC), shadow=shadow)+ msg = FlagsCacheInvalidation(team_id=team_id, emitted_at=datetime.now(UTC), shadow=shadow, source=source)with producer_scope(topic=KAFKA_FLAGS_CACHE_INVALIDATION, flush_timeout=0) as producer:producer.produce(topic=KAFKA_FLAGS_CACHE_INVALIDATION,@@ -1251,8 +1375,15 @@ def _produce_invalidation(team_id: int, shadow: bool = False) -> None:)except Exception as e:logger.warning(- "flags_cache_invalidation_produce_failed", team_id=team_id, shadow=shadow, error=str(e), exc_info=True+ "flags_cache_invalidation_produce_failed",+ team_id=team_id,+ shadow=shadow,+ source=source,+ error=str(e),+ exc_info=True,)+ if raise_on_error:+ raisedef _enqueue_invalidation(team_id: int) -> None:diff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.pyindex 34fafa034707..ebbb46339bab 100644--- a/products/feature_flags/backend/tasks.py+++ b/products/feature_flags/backend/tasks.py@@ -259,6 +259,14 @@ def refresh_expiring_flags_cache_entries(self: PushGatewayTask) -> None:"Number of flags caches that failed to refresh",registry=self.metrics_registry,)+ # Separate from the successful gauge because an enqueued team has not been rebuilt+ # yet when the run ends. Folding the two together would report a healthy sweep+ # while the Kafka builder was down.+ enqueued_gauge = Gauge(+ "posthog_flags_cache_refresh_enqueued_count",+ "Number of flags caches whose refresh was raised as a Kafka invalidation instead of being built here",+ registry=self.metrics_registry,+ )start_time = time.time()logger.info(@@ -275,6 +283,7 @@ def refresh_expiring_flags_cache_entries(self: PushGatewayTask) -> None:# Record metricssuccessful_gauge.set(counts.successful)failed_gauge.set(counts.failed)+ enqueued_gauge.set(counts.enqueued)# Note: Teams processed metrics are pushed to Pushgateway by# cache_expiry_manager.refresh_expiring_caches() via push_hypercache_teams_processed_metrics()@@ -288,6 +297,7 @@ def refresh_expiring_flags_cache_entries(self: PushGatewayTask) -> None:"Completed flags cache refresh",successful_refreshes=counts.successful,failed_refreshes=counts.failed,+ enqueued_refreshes=counts.enqueued,total_cached=stats_after.get("total_cached", 0),total_teams=stats_after.get("total_teams", 0),cache_coverage=stats_after.get("cache_coverage", "unknown"),diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex c32f907afc5e..47a1adc6ae88 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -29,13 +29,14 @@ from parameterized import parameterizedfrom posthog.kafka_client.topics import KAFKA_FLAGS_CACHE_INVALIDATIONfrom posthog.models import Team-from posthog.storage.cache_expiry_manager import CacheRefreshCounts+from posthog.storage.cache_expiry_manager import CacheRefreshCounts, RefreshPacingfrom products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.flags_cache import (FLAGS_HYPERCACHE_MANAGEMENT_CONFIG,KAFKA_ROUTING_FLAG,+ REFRESH_ROUTING_FLAG,SHADOW_COMPARE_FLAG,_blank_inactive_filters,_compare_flag_fields,@@ -55,6 +56,7 @@ from products.feature_flags.backend.flags_cache import (get_team_primary_flags_writer,get_teams_with_flags_queryset,publish_shadow_invalidation,+ route_refresh_to_kafka,update_flags_cache,verify_team_flags,)@@ -858,6 +860,10 @@ class TestServiceFlagsKafkaRouting(BaseTest):assert envelope.version == 1assert envelope.team_id == self.team.idassert envelope.operation == "invalidate"+ # A builder that predates `source` rejects any message carrying it through+ # deny_unknown_fields, and counts it as a parse error the DLQ does not keep.+ # The edit path must stay on the default so it reaches those builders.+ assert "source" not in data@patch("products.feature_flags.backend.flags_cache.producer_scope")@patch("products.feature_flags.backend.flags_cache._route_to_kafka", return_value=True)@@ -990,6 +996,76 @@ class TestServiceFlagsKafkaRouting(BaseTest):mock_produce.assert_not_called()+@override_settings(FLAGS_CACHE_REFRESH_KAFKA_ENABLED=True)+class TestRefreshRoutingHook(SimpleTestCase):+ TEAM_ID = 11++ @override_settings(FLAGS_CACHE_REFRESH_KAFKA_ENABLED=False)+ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch("products.feature_flags.backend.flags_cache.feature_enabled_or_false", return_value=True)+ def test_the_deployment_switch_off_declines_the_team_without_reading_the_flag(self, mock_gate, mock_produce):+ assert route_refresh_to_kafka(self.TEAM_ID) is False++ # Checked before the flag, which resolves against one project key for every+ # region and so cannot hold routing off in the lagging one.+ mock_gate.assert_not_called()+ mock_produce.assert_not_called()++ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch("products.feature_flags.backend.flags_cache.feature_enabled_or_false", return_value=False)+ def test_gate_off_declines_the_team_and_produces_nothing(self, mock_gate, mock_produce):+ assert route_refresh_to_kafka(self.TEAM_ID) is False++ mock_produce.assert_not_called()+ # The sweep must not read the edit path's flag, which is pinned at 100%.+ assert mock_gate.call_args.args[0] == REFRESH_ROUTING_FLAG+ assert REFRESH_ROUTING_FLAG != KAFKA_ROUTING_FLAG++ @patch("products.feature_flags.backend.flags_cache.producer_scope")+ @patch("products.feature_flags.backend.flags_cache.feature_enabled_or_false", return_value=True)+ def test_gate_on_produces_a_message_the_builder_reads_as_a_refresh(self, mock_gate, mock_producer_scope):+ mock_producer = MagicMock()+ mock_producer_scope.return_value.__enter__.return_value = mock_producer++ assert route_refresh_to_kafka(self.TEAM_ID) is True++ produce_kwargs = mock_producer.produce.call_args.kwargs+ assert produce_kwargs["key"] == str(self.TEAM_ID)+ envelope = FlagsCacheInvalidation.model_validate(produce_kwargs["data"])+ assert envelope.team_id == self.TEAM_ID+ assert envelope.source == "refresh"+ assert envelope.shadow is False++ @patch("products.feature_flags.backend.flags_cache.TOMBSTONE_COUNTER")+ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch(+ "products.feature_flags.backend.flags_cache.feature_enabled_or_false",+ side_effect=RuntimeError("posthoganalytics borked"),+ )+ def test_a_broken_gate_leaves_the_build_to_python_without_ticking_the_tombstone(+ self, mock_gate, mock_produce, mock_tombstone+ ):+ assert route_refresh_to_kafka(self.TEAM_ID) is False++ mock_produce.assert_not_called()+ # A run evaluates the gate once per team, so a tick here would hold a constant+ # rate on a panel that means "rare anomaly".+ mock_tombstone.labels.assert_not_called()++ @patch("products.feature_flags.backend.flags_cache.producer_scope")+ @patch("products.feature_flags.backend.flags_cache.feature_enabled_or_false", return_value=True)+ def test_a_produce_failure_is_reported_rather_than_counted_as_enqueued(self, mock_gate, mock_producer_scope):+ mock_producer_scope.side_effect = RuntimeError("kafka cluster unreachable")++ # Never True: the sweep counts a team as enqueued from this returning True, so+ # returning it here would report a hand-off that never happened for every team+ # of a run whose producer is down. The sweep turns the error into a failed team+ # and still skips its own Python build, which the hook contract test in+ # posthog/storage/test/test_cache_expiry_manager.py pins.+ with pytest.raises(RuntimeError, match="kafka cluster unreachable"):+ route_refresh_to_kafka(self.TEAM_ID)++class TestShadowInvalidationPublishing(SimpleTestCase):"""Shadow parity publishing. It runs at the tail of the Celery build ratherthan at invalidation time, so the Rust builder diffs against a cache entry@@ -1125,25 +1201,29 @@ class TestShadowInvalidationPublishing(SimpleTestCase):# the gate reports its own failure as "shadow off".assert mock_logger.warning.call_args.args[0] == "flags_cache_shadow_compare_flag_evaluation_failed"+ @override_settings(FLAGS_CACHE_REFRESH_KAFKA_ENABLED=True)@patch("products.feature_flags.backend.flags_cache._produce_invalidation")# `_shadow_compare_enabled` reaches the SDK through ph_client rather than this# module's import. Patching here still covers it, because both names resolve to# the same posthoganalytics module object.@patch("products.feature_flags.backend.flags_cache.posthoganalytics.feature_enabled", return_value=False)- def test_both_gates_evaluate_locally_and_capture_nothing(self, mock_feature_enabled, mock_produce):+ def test_every_gate_evaluates_locally_and_captures_nothing(self, mock_feature_enabled, mock_produce):publish_shadow_invalidation(self.TEAM_ID)+ route_refresh_to_kafka(self.TEAM_ID)# A remote evaluation would put a blocking flags-API call inside every cache- # build, and an event capture would bill each rebuild as product usage.+ # build, and an event capture would bill each rebuild as product usage. The+ # refresh gate runs once per team of every hourly run, so it costs the most.assert {call.args[0] for call in mock_feature_enabled.call_args_list} == {KAFKA_ROUTING_FLAG,SHADOW_COMPARE_FLAG,+ REFRESH_ROUTING_FLAG,}for call in mock_feature_enabled.call_args_list:assert call.kwargs["only_evaluate_locally"] is Trueassert call.kwargs["send_feature_flag_events"] is False- # Inert at 0%. This is the only test that runs the real gate, so nothing- # else catches it publishing while SHADOW_COMPARE_FLAG is off.+ # Inert at 0%. This is the only test that runs the real gates, so nothing+ # else catches one publishing while its flag is off.mock_produce.assert_not_called()@@ -1190,6 +1270,23 @@ class TestGetTeamPrimaryFlagsWriter(unittest.TestCase):assert FLAGS_HYPERCACHE_MANAGEMENT_CONFIG.get_primary_writer_fn(42) == "rust"assert mock_feature_enabled.call_args.args[1] == "team-42"+ @override_settings(FLAGS_CACHE_REFRESH_KAFKA_ENABLED=True)+ def test_flags_config_binds_the_refresh_routing_hook(self):+ # The lambda on the config is the only wire between the sweep and the hook.+ # Unbound, the sweep silently keeps building in Python and the enqueued gauge+ # stays at zero, which looks the same as the flag being off.+ with (+ patch("products.feature_flags.backend.flags_cache._produce_invalidation") as mock_produce,+ patch(+ "products.feature_flags.backend.flags_cache.feature_enabled_or_false",+ return_value=True,+ ),+ ):+ assert FLAGS_HYPERCACHE_MANAGEMENT_CONFIG.route_refresh_fn is not None+ assert FLAGS_HYPERCACHE_MANAGEMENT_CONFIG.route_refresh_fn(42) is True++ assert mock_produce.call_args.kwargs["source"] == "refresh"+@override_settings(FLAGS_REDIS_URL="redis://test")class TestServiceFlagsCeleryTasks(BaseTest):@@ -1914,8 +2011,18 @@ class TestBatchOperations(BaseTest):self.assertEqual(counts.successful, 2)self.assertEqual(counts.failed, 0)- # Should call generic refresh_expiring_caches with correct config- mock_refresh.assert_called_once_with(FLAGS_HYPERCACHE_MANAGEMENT_CONFIG, 24, settings.FLAGS_CACHE_REFRESH_LIMIT)+ # Should call generic refresh_expiring_caches with correct config, and take the+ # pacing for routed teams from settings rather than pinning it in code.+ mock_refresh.assert_called_once_with(+ FLAGS_HYPERCACHE_MANAGEMENT_CONFIG,+ 24,+ settings.FLAGS_CACHE_REFRESH_LIMIT,+ pacing=RefreshPacing(+ chunk_size=settings.FLAGS_CACHE_REFRESH_KAFKA_CHUNK_SIZE,+ delay_seconds=settings.FLAGS_CACHE_REFRESH_KAFKA_CHUNK_DELAY_SECONDS,+ window_seconds=settings.FLAGS_CACHE_REFRESH_KAFKA_WINDOW_SECONDS,+ ),+ )@patch("posthog.storage.cache_expiry_manager.get_client")def test_cleanup_stale_expiry_tracking(self, mock_get_client):