: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): make the expiry sweep backlog readable (#103572)
James Gillbc5fe763d868
diff --git a/posthog/storage/cache_expiry_manager.py b/posthog/storage/cache_expiry_manager.pyindex d530ee794ae3..d65efbf1f552 100644--- a/posthog/storage/cache_expiry_manager.py+++ b/posthog/storage/cache_expiry_manager.py@@ -23,9 +23,27 @@ logger = structlog.get_logger(__name__)RefreshOutcome = Literal["successful", "failed", "enqueued"]-def get_teams_with_expiring_caches(+@frozen+class ExpiringTeamSelection:+ """The teams one run will refresh, and whether Redis had more to give.++ `limit_reached` is read from the sorted-set range and not from `len(teams)`. A range+ that comes back full of identifiers for deleted teams resolves to fewer Team rows+ than it read, and the run is still leaving work behind. It is None when the range+ could not be read, because a run that never saw the queue cannot report on it.++ The range is capped at the limit, so a run that drained the queue exactly reports+ True as well. `ExpiryBacklogSample.due_count` is the unbounded reading that tells+ those two apart; this flag is the cheap signal on top of it, not a substitute.+ """++ teams: list[Team]+ limit_reached: bool | None+++def select_expiring_teams(config: HyperCacheManagementConfig, ttl_threshold_hours: int = 24, limit: int = 5000-) -> list[Team]:+) -> ExpiringTeamSelection:"""Get teams whose caches are expiring soon using sorted set for efficient lookup.@@ -38,13 +56,13 @@ def get_teams_with_expiring_caches(limit: Maximum number of teams to return (default 5000, prevents unbounded results)Returns:- List of Team objects whose caches need refresh (up to limit)+ The teams whose caches need refresh (up to limit), and whether the range filled"""hypercache = config.hypercacheif not hypercache.expiry_sorted_set_key:logger.warning(f"No expiry sorted set configured for {config.log_prefix}")- return []+ return ExpiringTeamSelection(teams=[], limit_reached=False)try:redis_client = get_client(hypercache.redis_url)@@ -57,9 +75,11 @@ def get_teams_with_expiring_caches(hypercache.expiry_sorted_set_key, "-inf", threshold_timestamp, start=0, num=limit)+ limit_reached = len(expiring_identifiers) >= limit+if not expiring_identifiers:logger.info(f"No {config.log_prefix} expiring soon")- return []+ return ExpiringTeamSelection(teams=[], limit_reached=False)# Decode bytes to strings and convert to appropriate type based on token_basedquery_field = "api_token" if hypercache.token_based else "id"@@ -79,49 +99,93 @@ def get_teams_with_expiring_caches(f"Found teams with expiring {config.log_prefix}",team_count=len(teams),ttl_threshold_hours=ttl_threshold_hours,+ limit_reached=limit_reached,)- return teams+ return ExpiringTeamSelection(teams=teams, limit_reached=limit_reached)except Exception as e:logger.exception(f"Error finding expiring {config.log_prefix}", error=str(e))capture_exception(e)- return []+ return ExpiringTeamSelection(teams=[], limit_reached=None)-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.+def get_teams_with_expiring_caches(+ config: HyperCacheManagementConfig, ttl_threshold_hours: int = 24, limit: int = 5000+) -> list[Team]:+ """Teams whose caches are expiring soon, for callers that do not report on the run."""+ return select_expiring_teams(config, ttl_threshold_hours, limit).teams+++@frozen+class ExpiryBacklogSample:+ """One reading of the expiry sorted set, taken at a single moment.- 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+ `due_count` is deliberately unbounded, unlike `select_expiring_teams`, which stops at+ the run's limit. The count is the sweep's saturation signal: it has to be able toexceed what one run processes, or it cannot tell a drained queue from a queue thesweep is falling behind on.+ `oldest_seconds_to_expiry` answers the question the count has only ever been a proxy+ for: is anything about to expire before the sweep reaches it. Unlike the count it is+ not inflated by refreshes already in flight. It is not immune to members left behind+ for deleted teams, though: such a member is never re-scored, so it holds the set's+ minimum and pins this reading until `cleanup_stale_expiry_tracking` removes it, and+ that cleanup is a daily task where it is scheduled at all.++ Both are None when Redis does not answer, which pushes no series rather than a zero+ that reads as a drained queue.+ """++ due_count: int | None+ oldest_seconds_to_expiry: float | None+++def sample_expiry_backlog(config: HyperCacheManagementConfig, ttl_threshold_hours: int = 24) -> ExpiryBacklogSample:+ """+ Read the expiry tracking sorted set: how much is due, and how urgent the worst is.+Args:- config: HyperCache management config specifying which cache to count+ config: HyperCache management config specifying which cache to readttl_threshold_hours: Count entries expiring within this many hoursReturns:- Number of entries due for refresh, or None if the count is unavailable+ The reading, with None fields when the sorted set cannot be read"""hypercache = config.hypercacheif not hypercache.expiry_sorted_set_key:- return None+ return ExpiryBacklogSample(due_count=None, oldest_seconds_to_expiry=None)try:redis_client = get_client(hypercache.redis_url)- return redis_client.zcount(hypercache.expiry_sorted_set_key, "-inf", _expiry_threshold(ttl_threshold_hours))+ # One clock for both readings, so the count and the age describe the same moment.+ now = time.time()+ due_count = redis_client.zcount(+ hypercache.expiry_sorted_set_key, "-inf", _expiry_threshold(ttl_threshold_hours, now)+ )+ except Exception as e:+ logger.warning(f"Error reading expiry backlog for {config.log_prefix}", error=str(e))+ return ExpiryBacklogSample(due_count=None, oldest_seconds_to_expiry=None)++ # Guarded separately from the count so that a zrange failure does not discard a+ # zcount that already succeeded.+ try:+ oldest = redis_client.zrange(hypercache.expiry_sorted_set_key, 0, 0, withscores=True)+ # The score is the expiration timestamp, so the value goes negative once the+ # oldest entry is past its expiry and the sweep is behind.+ oldest_seconds = oldest[0][1] - now if oldest else Noneexcept Exception as e:- logger.warning(f"Error counting expiring {config.log_prefix}", error=str(e))- return None+ logger.warning(f"Error reading oldest expiry entry for {config.log_prefix}", error=str(e))+ oldest_seconds = None+ return ExpiryBacklogSample(due_count=due_count, oldest_seconds_to_expiry=oldest_seconds)-def _expiry_threshold(ttl_threshold_hours: int) -> float:++def _expiry_threshold(ttl_threshold_hours: int, now: float | None = None) -> float:"""The sorted-set score below which an entry is due for refresh. Shared so thebacklog gauge always describes the same set the sweep pulls its teams from."""- return time.time() + (ttl_threshold_hours * 3600)+ return (time.time() if now is None else now) + (ttl_threshold_hours * 3600)@frozen@@ -168,8 +232,45 @@ class RefreshPacing:raise ValueError("pacing delays must not be negative")+@frozen+class RefreshRun:+ """Everything a run reads before it touches a team.++ Built in one place because the order matters. Once the run starts, a config with a+ routing hook produces messages for another builder, and those teams stay in the+ sorted set until that builder rebuilds them seconds to minutes later. A backlog+ sample taken after that point counts work that is already in flight, so the only+ clean reading of the queue is the one taken before the first team is processed.++ `ttl_threshold_hours` rides along so the after sample counts the same set the before+ sample did. Passed separately to both ends, the two could drift and their difference+ would stop meaning anything.+ """++ backlog_before: ExpiryBacklogSample+ teams: list[Team]+ limit_reached: bool | None+ ttl_threshold_hours: int+++def start_refresh_run(+ config: HyperCacheManagementConfig, ttl_threshold_hours: int = 24, limit: int = 5000+) -> RefreshRun:+ """Sample the expiry backlog, then pick the teams this run will refresh."""+ backlog_before = sample_expiry_backlog(config, ttl_threshold_hours)+ selection = select_expiring_teams(config, ttl_threshold_hours, limit)+ return RefreshRun(+ backlog_before=backlog_before,+ teams=selection.teams,+ limit_reached=selection.limit_reached,+ ttl_threshold_hours=ttl_threshold_hours,+ )++def push_refresh_metrics(- config: HyperCacheManagementConfig, counts: CacheRefreshCounts, ttl_threshold_hours: int = 24+ config: HyperCacheManagementConfig,+ run: RefreshRun,+ counts: CacheRefreshCounts,) -> None:"""Push a refresh run's counts and its expiry backlog to Pushgateway.@@ -178,16 +279,37 @@ def push_refresh_metrics(in remote_config_cache. One function so the next field added reaches both withoutanyone having to remember the fork exists.+ Both ends of the run are pushed, because neither reading means anything alone. The+ before sample is the clean one, taken before the run touches a team.++ A member leaves the due window only when something writes its cache and re-scores it.+ So `before - after` is what a run that builds its own teams drained. A run that routes+ its refreshes writes nothing, so its teams hold their scores until the other builder+ rebuilds them, and the same subtraction returns close to zero.++ One run's before sample minus the previous run's after sample is the net change+ between runs, not an arrival rate. Rebuilds that complete in the gap re-score out of+ the window and cancel part of the arrivals.++ To see whether the queue is growing, read the before series run over run. Its slope is+ arrivals minus completions, so a rising series means the sweep is falling behind.+ Nothing here counts entries as they enter the window.+An empty run pushes too. Pushgateway keeps serving the last value pushed, soskipping it would latch a drained backlog at whatever the last busy run saw."""+ backlog_after = sample_expiry_backlog(config, run.ttl_threshold_hours)+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),+ expiry_backlog=backlog_after.due_count,+ expiry_backlog_before=run.backlog_before.due_count,+ oldest_expiry_seconds=run.backlog_before.oldest_seconds_to_expiry,+ limit_reached=run.limit_reached,)@@ -201,7 +323,8 @@ def refresh_expiring_caches(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)+ 1. Samples the expiry backlog, then finds teams whose caches are expiring within the+ threshold (up to limit)2. Refreshes each cache, either by calling the configured update function or, whenthe config binds a routing hook that claims the team, by handing the refresh tothe builder behind that hook@@ -221,18 +344,20 @@ def refresh_expiring_caches(Returns:CacheRefreshCounts with successful, failed and enqueued counts"""- teams = get_teams_with_expiring_caches(config, ttl_threshold_hours, limit)- counts = _refresh_teams(config, teams, pacing)+ run = start_refresh_run(config, ttl_threshold_hours, limit)+ counts = _refresh_teams(config, run.teams, pacing)logger.info(f"Completed refreshing {config.log_prefix}",successful=counts.successful,failed=counts.failed,enqueued=counts.enqueued,- total=len(teams),+ total=len(run.teams),+ limit_reached=run.limit_reached,+ backlog_before=run.backlog_before.due_count,)- push_refresh_metrics(config, counts, ttl_threshold_hours)+ push_refresh_metrics(config, run, counts)return countsdiff --git a/posthog/storage/hypercache_manager.py b/posthog/storage/hypercache_manager.pyindex 350ad7bbe934..91c3fefb3f92 100644--- a/posthog/storage/hypercache_manager.py+++ b/posthog/storage/hypercache_manager.py@@ -128,6 +128,9 @@ def push_hypercache_teams_processed_metrics(failed: int,enqueued: int = 0,expiry_backlog: int | None = None,+ expiry_backlog_before: int | None = None,+ oldest_expiry_seconds: float | None = None,+ limit_reached: bool | None = None,) -> None:"""Push teams processed metrics to Pushgateway after batch refresh operations.@@ -151,10 +154,48 @@ def push_hypercache_teams_processed_metrics(expiry_backlog: Entries in the expiry sorted set that are due for refresh,sampled after the run. None when the count is unavailable, which pushesno series rather than a zero that reads as a drained queue.+ expiry_backlog_before: The same count, sampled before the run started. See+ `RefreshRun` in `cache_expiry_manager` for why the before sample is the+ one to trust.+ oldest_expiry_seconds: Seconds until the oldest tracked entry expires, sampled+ before the run started. Negative once that entry is past its expiry.+ limit_reached: Whether the run took as many teams as its limit allowed. Read+ from the sorted-set range, which is capped at the limit, so a run that+ drained the queue exactly also reports True. `expiry_backlog_before` is+ the unbounded count and settles that case. None when the caller cannot+ tell, which pushes no series.++ Every optional value is dropped when None. The push is a PUT that replaces the whole+ job, so a dropped series disappears from Pushgateway rather than holding its previous+ reading. The gap is the signal: it says Redis did not answer, where a zero would say+ the queue is drained. Alert on absence, not on a stale value."""if not settings.PROM_PUSHGATEWAY_ADDRESS:return+ run_gauges = [+ (+ "posthog_hypercache_expiry_backlog_last_run",+ "Entries due for refresh in the expiry sorted set, sampled after the last batch refresh run",+ expiry_backlog,+ ),+ (+ "posthog_hypercache_expiry_backlog_before_run",+ "Entries due for refresh in the expiry sorted set, sampled before the last batch refresh run started",+ expiry_backlog_before,+ ),+ (+ "posthog_hypercache_expiry_oldest_before_run_seconds",+ "Seconds until the oldest tracked entry expires, sampled before the last batch refresh run started, negative once it is past expiry",+ oldest_expiry_seconds,+ ),+ (+ "posthog_hypercache_refresh_limit_reached_last_run",+ "1 when the last batch refresh run took as many teams as its limit allowed, 0 otherwise",+ None if limit_reached is None else int(limit_reached),+ ),+ ]+try:with pushed_metrics_registry(f"hypercache_teams_processed_{namespace}_{cache_name}") as registry:success_gauge = Gauge(@@ -167,14 +208,11 @@ def push_hypercache_teams_processed_metrics(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)+ for name, description, value in run_gauges:+ if value is None:+ continue+ gauge = Gauge(name, description, labelnames=["namespace", "cache_name"], registry=registry)+ gauge.labels(namespace=namespace, cache_name=cache_name).set(value)except Exception as e:logger.warning("Failed to push hypercache teams processed to Pushgateway",@@ -229,7 +267,7 @@ class HyperCacheManagementConfig:repair_miss_during_grace_period: bool = False# Team columns the refresh/warm path reads off each Team object. When set,- # get_teams_with_expiring_caches narrows its SELECT to these columns via .only()+ # select_expiring_teams narrows its SELECT to these columns via .only()# instead of fetching the whole row. This keeps the refresh working when a Team# column added by a migration the read replica hasn't applied yet would otherwise# make `SELECT *` raise UndefinedColumn (the replica lags on posthog_team DDL).diff --git a/posthog/storage/remote_config_cache.py b/posthog/storage/remote_config_cache.pyindex 2e24f765d14a..3c5161fbc06c 100644--- a/posthog/storage/remote_config_cache.py+++ b/posthog/storage/remote_config_cache.py@@ -23,8 +23,8 @@ from posthog.models.team.team import Teamfrom 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,+ start_refresh_run,)from posthog.storage.hypercache_manager import (HyperCacheManagementConfig,@@ -91,12 +91,12 @@ def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) ->Batch-loads every expiring team's config in one query — the config lives in a separatetable 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)+ run = start_refresh_run(REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours, limit)# 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"))+ team_by_id = {team.id: team for team in run.teams}+ configs = dict(RemoteConfig.objects.filter(team__in=run.teams).values_list("team_id", "config"))successful = 0failed = 0@@ -115,7 +115,7 @@ def refresh_expiring_caches(ttl_threshold_hours: int = 24, limit: int = 5000) ->failed += 1counts = CacheRefreshCounts(successful=successful, failed=failed)- push_refresh_metrics(REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG, counts, ttl_threshold_hours)+ push_refresh_metrics(REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG, run, counts)return countsdiff --git a/posthog/storage/test/test_cache_expiry_manager.py b/posthog/storage/test/test_cache_expiry_manager.pyindex 2b23b5006fbe..5e85b2c6af7d 100644--- a/posthog/storage/test/test_cache_expiry_manager.py+++ b/posthog/storage/test/test_cache_expiry_manager.py@@ -7,7 +7,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom posthog.models.team.team import Team-from posthog.storage.cache_expiry_manager import RefreshPacing, refresh_expiring_caches+from posthog.storage.cache_expiry_manager import ExpiringTeamSelection, RefreshPacing, refresh_expiring_cachesfrom posthog.storage.test.test_hypercache_manager import create_test_config as build_configMODULE = "posthog.storage.cache_expiry_manager"@@ -20,16 +20,18 @@ def build_teams(count: int) -> list[Team]: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)+ select_patcher = patch(f"{MODULE}.select_expiring_teams")+ self.mock_select = select_patcher.start()+ self.addCleanup(select_patcher.stop)+ self.given_teams(3)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+ self.mock_redis = self.mock_get_client.return_value+ self.mock_redis.zcount.return_value = 0+ self.mock_redis.zrange.return_value = []push_patcher = patch(f"{MODULE}.push_hypercache_teams_processed_metrics")self.mock_push = push_patcher.start()@@ -45,6 +47,9 @@ class TestRefreshExpiringCaches(SimpleTestCase):self.mock_sleep = mock_time.sleepself.addCleanup(time_patcher.stop)+ def given_teams(self, count: int, limit_reached: bool = False) -> None:+ self.mock_select.return_value = ExpiringTeamSelection(teams=build_teams(count), limit_reached=limit_reached)+def test_without_a_routing_hook_every_team_is_built(self):update_fn = MagicMock(return_value=True)@@ -74,7 +79,7 @@ class TestRefreshExpiringCaches(SimpleTestCase):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)+ self.given_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")])@@ -106,7 +111,7 @@ class TestRefreshExpiringCaches(SimpleTestCase):])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))+ self.given_teams(len(routed))refresh_expiring_caches(build_config(route_refresh_fn=MagicMock(side_effect=routed)),@@ -116,7 +121,7 @@ class TestRefreshExpiringCaches(SimpleTestCase):assert [call.args[0] for call in self.mock_sleep.call_args_list] == expected_delaysdef test_pacing_stops_once_the_window_is_spent(self):- self.mock_get_teams.return_value = build_teams(5)+ self.given_teams(5)refresh_expiring_caches(build_config(route_refresh_fn=MagicMock(return_value=True)),@@ -127,19 +132,72 @@ class TestRefreshExpiringCaches(SimpleTestCase):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+ self.mock_redis.zcount.return_value = 9000refresh_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"+ assert self.mock_redis.zcount.call_args.args[0] == "test_cache_expiry"+ assert self.mock_redis.zcount.call_args.args[1] == "-inf"++ def test_the_before_sample_is_taken_before_any_team_is_processed(self) -> None:+ backlog = [9000]+ self.mock_redis.zcount.side_effect = lambda *args, **kwargs: backlog[0]++ def route_refresh_fn(_team_id: int) -> bool:+ backlog[0] = 0+ return True++ refresh_expiring_caches(build_config(route_refresh_fn=route_refresh_fn))++ push_kwargs = self.mock_push.call_args.kwargs+ # A before sample taken after the run starts reads whatever the run has already+ # done to the sorted set, which is the ambiguity this pair of samples removes.+ assert push_kwargs["expiry_backlog_before"] == 9000+ assert push_kwargs["expiry_backlog"] == 0++ @parameterized.expand(+ [+ ("due_in_an_hour", 3600),+ ("an_hour_past_expiry", -3600),+ ]+ )+ def test_the_oldest_entry_is_reported_as_seconds_until_its_expiry(self, _name: str, seconds_to_expiry: int) -> None:+ # The two reads are the before and after samples. Only the before one is pushed,+ # so they have to differ or forwarding the wrong sample passes this test.+ self.mock_redis.zrange.side_effect = [+ [(b"7", time.time() + seconds_to_expiry)],+ [(b"7", time.time() + 86400)],+ ]++ refresh_expiring_caches(build_config())++ self.assertAlmostEqual(self.mock_push.call_args.kwargs["oldest_expiry_seconds"], seconds_to_expiry, delta=5)+ # The lowest score is the entry closest to expiry. Reading the other end of the+ # set reports the healthiest entry and hides a sweep that is falling behind.+ assert self.mock_redis.zrange.call_args.args == ("test_cache_expiry", 0, 0)+ assert self.mock_redis.zrange.call_args.kwargs == {"withscores": True}++ def test_an_empty_sorted_set_reports_no_oldest_entry(self) -> None:+ self.mock_redis.zrange.return_value = []++ refresh_expiring_caches(build_config())++ assert self.mock_push.call_args.kwargs["oldest_expiry_seconds"] is None++ @parameterized.expand([("saturated", True), ("drained", False)])+ def test_the_run_reports_whether_its_selection_filled(self, _name: str, limit_reached: bool) -> None:+ self.given_teams(3, limit_reached=limit_reached)++ refresh_expiring_caches(build_config())++ assert self.mock_push.call_args.kwargs["limit_reached"] is limit_reacheddef 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+ self.given_teams(0)+ self.mock_redis.zcount.return_value = 0refresh_expiring_caches(build_config())@@ -148,10 +206,25 @@ class TestRefreshExpiringCaches(SimpleTestCase):assert push_kwargs["failed"] == 0assert push_kwargs["enqueued"] == 0assert push_kwargs["expiry_backlog"] == 0+ assert push_kwargs["expiry_backlog_before"] == 0def 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 None+ push_kwargs = self.mock_push.call_args.kwargs+ assert push_kwargs["expiry_backlog"] is None+ assert push_kwargs["expiry_backlog_before"] is None+ assert push_kwargs["oldest_expiry_seconds"] is None++ def test_an_unreadable_oldest_entry_still_reports_the_count(self) -> None:+ self.mock_redis.zcount.return_value = 9000+ self.mock_redis.zrange.side_effect = RuntimeError("redis timed out")++ refresh_expiring_caches(build_config())++ # A zrange failure must not discard a zcount that already succeeded.+ push_kwargs = self.mock_push.call_args.kwargs+ assert push_kwargs["expiry_backlog_before"] == 9000+ assert push_kwargs["oldest_expiry_seconds"] is Nonediff --git a/posthog/storage/test/test_hypercache_manager.py b/posthog/storage/test/test_hypercache_manager.pyindex a0534c22521f..90c03c4708c0 100644--- a/posthog/storage/test/test_hypercache_manager.py+++ b/posthog/storage/test/test_hypercache_manager.py@@ -477,6 +477,9 @@ class TestPushHypercacheTeamsProcessedMetrics(BaseTest):failed=100,enqueued=25,expiry_backlog=7000,+ expiry_backlog_before=11000,+ oldest_expiry_seconds=-1800.0,+ limit_reached=True,)mock_registry_cm.assert_called_once_with("hypercache_teams_processed_feature_flags_flags")@@ -496,6 +499,12 @@ class TestPushHypercacheTeamsProcessedMetrics(BaseTest):# 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+ # The before sample is what the after sample is read against: 11000 - 7000 is what+ # the run drained, and the next run's before sample against 7000 is the net change+ # between runs.+ assert registry.get_sample_value("posthog_hypercache_expiry_backlog_before_run", base) == 11000+ assert registry.get_sample_value("posthog_hypercache_expiry_oldest_before_run_seconds", base) == -1800.0+ assert registry.get_sample_value("posthog_hypercache_refresh_limit_reached_last_run", base) == 1@patch("posthog.storage.hypercache_manager.pushed_metrics_registry")def test_an_unavailable_backlog_emits_no_backlog_series(self, mock_registry_cm):@@ -510,17 +519,44 @@ class TestPushHypercacheTeamsProcessedMetrics(BaseTest):successful=900,failed=100,expiry_backlog=None,+ expiry_backlog_before=None,+ oldest_expiry_seconds=None,+ limit_reached=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_expiry_backlog_before_run", base) is None+ assert registry.get_sample_value("posthog_hypercache_expiry_oldest_before_run_seconds", base) is None+ # A 0 here would read as a run that saw the whole queue and left nothing behind.+ assert registry.get_sample_value("posthog_hypercache_refresh_limit_reached_last_run", base) is Noneassert (registry.get_sample_value("posthog_hypercache_teams_processed_last_run", {**base, "result": "success"})== 900)+ @patch("posthog.storage.hypercache_manager.pushed_metrics_registry")+ def test_a_run_that_stayed_under_its_limit_pushes_a_zero(self, mock_registry_cm: MagicMock) -> None:+ 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,+ limit_reached=False,+ )++ base = {"namespace": "feature_flags", "cache_name": "flags"}+ # Dropping a known False on falsiness would remove the series, which a consumer+ # cannot tell apart from a run that could not read the queue at all.+ assert registry.get_sample_value("posthog_hypercache_refresh_limit_reached_last_run", base) == 0+@patch("posthog.storage.hypercache_manager.pushed_metrics_registry")def test_skips_push_when_no_pushgateway_address(self, mock_registry_cm):"""No push happens when PROM_PUSHGATEWAY_ADDRESS is not set."""diff --git a/posthog/storage/test/test_remote_config_cache.py b/posthog/storage/test/test_remote_config_cache.pyindex a7ff3c97f6d4..d8250cfa5c5f 100644--- a/posthog/storage/test/test_remote_config_cache.py+++ b/posthog/storage/test/test_remote_config_cache.py@@ -1,3 +1,5 @@+import time+from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -98,6 +100,27 @@ class TestRefreshExpiringRemoteConfigCaches(BaseTest):assert push_kwargs["failed"] == 0assert push_kwargs["expiry_backlog"] == 0+ @patch("posthog.storage.cache_expiry_manager.push_hypercache_teams_processed_metrics")+ @patch("posthog.storage.cache_expiry_manager.get_client")+ def test_the_fork_reports_the_same_run_diagnostics_as_the_shared_sweep(+ self, mock_get_client: MagicMock, mock_push: MagicMock+ ) -> None:+ mock_redis = MagicMock()+ mock_get_client.return_value = mock_redis+ mock_redis.zrangebyscore.return_value = []+ mock_redis.zcount.side_effect = [40, 12]+ mock_redis.zrange.return_value = [(self.team.api_token.encode(), time.time() - 60)]++ refresh_expiring_caches(ttl_threshold_hours=24)++ # This fork selects its teams itself, so it is the one that can drift from the+ # shared sweep and report a bare count while every other cache reports a run.+ push_kwargs = mock_push.call_args.kwargs+ assert push_kwargs["expiry_backlog_before"] == 40+ assert push_kwargs["expiry_backlog"] == 12+ assert push_kwargs["limit_reached"] is False+ assert push_kwargs["oldest_expiry_seconds"] < 0+class TestCleanupStaleRemoteConfigExpiryTracking(BaseTest):@patch("posthog.storage.cache_expiry_manager.get_client")diff --git a/posthog/storage/test/test_team_metadata_cache.py b/posthog/storage/test/test_team_metadata_cache.pyindex 186d70d823c2..a4625ea212bd 100644--- a/posthog/storage/test/test_team_metadata_cache.py+++ b/posthog/storage/test/test_team_metadata_cache.py@@ -14,7 +14,9 @@ from parameterized import parameterizedimport posthog.storage.team_access_cache_signal_handlers # noqa: F401 — registers PSAK delete handlerfrom posthog.models.team.team import Team+from posthog.storage.cache_expiry_manager import select_expiring_teamsfrom posthog.storage.team_metadata_cache import (+ TEAM_HYPERCACHE_MANAGEMENT_CONFIG,TEAM_METADATA_FIELDS,_serialize_team_field,clear_team_metadata_cache,@@ -359,6 +361,31 @@ class TestGetTeamsWithExpiringCaches(BaseTest):self.assertEqual(len(result), 0)+ @patch("posthog.storage.cache_expiry_manager.get_client")+ def test_a_full_range_reports_the_limit_even_when_an_identifier_is_stale(self, mock_get_client: MagicMock) -> None:+ mock_redis = MagicMock()+ mock_get_client.return_value = mock_redis+ # The range comes back full, but one identifier belongs to a team that no longer+ # exists, which is the steady state of a sorted set the cleanup task has not reached.+ mock_redis.zrangebyscore.return_value = [self.team.api_token.encode(), b"phc_deleted_team"]++ selection = select_expiring_teams(TEAM_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours=24, limit=2)++ self.assertEqual(len(selection.teams), 1)+ # Reading the limit from the resolved teams would report this run as having room+ # to spare, while Redis still holds work it did not take.+ self.assertTrue(selection.limit_reached)++ @patch("posthog.storage.cache_expiry_manager.get_client")+ def test_an_unreadable_range_reports_the_limit_as_unknown(self, mock_get_client: MagicMock) -> None:+ mock_get_client.side_effect = RuntimeError("redis unreachable")++ selection = select_expiring_teams(TEAM_HYPERCACHE_MANAGEMENT_CONFIG, ttl_threshold_hours=24)++ # Reporting False here pushes a 0 that Pushgateway keeps serving, which states the+ # queue was drained by a run that never read it.+ self.assertIsNone(selection.limit_reached)+@patch("posthog.storage.cache_expiry_manager.get_client")def test_narrows_selected_columns_to_refresh_fields(self, mock_get_client):"""The refresh SELECT is narrowed via .only(), so a Team column the read replica