: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
fix(flags): narrow hypercache refresh team query to only needed columns (#68338)
posthog[bot]55899f0b4c87
diff --git a/posthog/storage/cache_expiry_manager.py b/posthog/storage/cache_expiry_manager.pyindex 1514f31d9bc5..133626db9912 100644--- a/posthog/storage/cache_expiry_manager.py+++ b/posthog/storage/cache_expiry_manager.py@@ -67,7 +67,15 @@ def get_teams_with_expiring_caches(# Build query filter dynamically based on token_based settingfilter_kwargs = {f"{query_field}__in": decoded_identifiers}- teams = list(Team.objects.filter(**filter_kwargs).select_related("organization", "project"))+ query = Team.objects.filter(**filter_kwargs).select_related("organization", "project")++ # Narrow the SELECT to the columns the refresh actually reads. Otherwise a+ # Team column from a migration the read replica hasn't applied yet makes the+ # implicit `SELECT *` raise UndefinedColumn and silently skip the whole batch.+ if config.refresh_only_fields is not None:+ query = query.only(*config.refresh_only_fields)++ teams = list(query)logger.info(f"Found teams with expiring {config.log_prefix}",diff --git a/posthog/storage/hypercache_manager.py b/posthog/storage/hypercache_manager.pyindex fc8e0b0e0b0e..7167f7f1fe0c 100644--- a/posthog/storage/hypercache_manager.py+++ b/posthog/storage/hypercache_manager.py@@ -209,6 +209,16 @@ class HyperCacheManagementConfig:# skip as an optimization and leave this False.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()+ # 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).+ # Must list every Team field the config's update_fn/load_fn reads; related fields+ # (organization/project) come via select_related and don't need listing, but the+ # FK columns (organization_id, project_id) do. Leave None to select all columns.+ refresh_only_fields: list[str] | None = None+# 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@@ -320,6 +330,9 @@ def warm_caches(else:teams_queryset = config.get_teams_queryset().select_related("organization", "project")+ if config.refresh_only_fields is not None:+ teams_queryset = teams_queryset.only(*config.refresh_only_fields)+total_teams = teams_queryset.count()logger.info(diff --git a/posthog/storage/remote_config_cache.py b/posthog/storage/remote_config_cache.pyindex fbe97d9fb903..5fa68d53a9a7 100644--- a/posthog/storage/remote_config_cache.py+++ b/posthog/storage/remote_config_cache.py@@ -72,6 +72,14 @@ REMOTE_CONFIG_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(hypercache=remote_config_hypercache,update_fn=update_remote_config_cache,cache_name="remote_config",+ # The refresh only needs the team id (to join RemoteConfig) and api_token (cache key+ # + expiry identifier). Narrowing the SELECT keeps it resilient to newly added Team+ # columns the read replica may not have applied yet. organization_id keeps the+ # (unused) organization/project select_related join valid.+ # This only protects the batch refresh_expiring_caches path below, not update_fn:+ # update_remote_config_cache re-fetches its own unrestricted Team, so it must never+ # run against a narrowed team instance from this config.+ refresh_only_fields=["id", "api_token", "project_id", "organization_id"],)diff --git a/posthog/storage/team_llm_gateway_policy_cache.py b/posthog/storage/team_llm_gateway_policy_cache.pyindex 75a8d620996b..ca62c793a297 100644--- a/posthog/storage/team_llm_gateway_policy_cache.py+++ b/posthog/storage/team_llm_gateway_policy_cache.py@@ -132,6 +132,10 @@ LLM_GATEWAY_POLICY_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(hypercache=team_llm_gateway_policy_hypercache,update_fn=update_team_llm_gateway_policy_cache,cache_name="llm_gateway_policy",+ # The refresh only projects these columns; narrowing the SELECT keeps it resilient+ # to newly added Team columns the read replica may not have applied yet. The FK ids+ # are included so the (unused) organization/project select_related join stays valid.+ refresh_only_fields=[*LLM_GATEWAY_POLICY_FIELDS, "project_id", "organization_id"],)diff --git a/posthog/storage/team_metadata_cache.py b/posthog/storage/team_metadata_cache.pyindex 4d73bd7c1504..257a15cde693 100644--- a/posthog/storage/team_metadata_cache.py+++ b/posthog/storage/team_metadata_cache.py@@ -410,6 +410,10 @@ TEAM_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(update_fn=update_team_metadata_cache,cache_name="team_metadata",get_team_ids_to_skip_fix_fn=_get_team_ids_with_recently_updated_teams,+ # The refresh serializes exactly these columns (plus organization/project names+ # via select_related), so narrowing the SELECT to them keeps the job resilient to+ # newly added Team columns the read replica may not have yet.+ refresh_only_fields=TEAM_METADATA_FIELDS,)diff --git a/posthog/storage/test/test_team_metadata_cache.py b/posthog/storage/test/test_team_metadata_cache.pyindex 8d7f254e3ec6..d192d1c0e8d8 100644--- a/posthog/storage/test/test_team_metadata_cache.py+++ b/posthog/storage/test/test_team_metadata_cache.py@@ -359,6 +359,27 @@ class TestGetTeamsWithExpiringCaches(BaseTest):self.assertEqual(len(result), 0)+ @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+ hasn't migrated yet can't turn the whole batch into an UndefinedColumn error.+ Guards against reverting to a `SELECT *` that fetches every column."""+ mock_redis = MagicMock()+ mock_get_client.return_value = mock_redis+ mock_redis.zrangebyscore.return_value = [self.team.api_token.encode()]++ with self.assertNumQueries(1):+ teams = get_teams_with_expiring_caches(ttl_threshold_hours=24)++ self.assertEqual(len(teams), 1)+ deferred = teams[0].get_deferred_fields()+ # Columns outside the refresh set are deferred (not fetched) — a SELECT * regression+ # would leave this empty.+ self.assertTrue(deferred)+ # Every column the refresh serializes is loaded, so serialization never triggers a+ # per-field lazy load.+ self.assertEqual(deferred & set(TEAM_METADATA_FIELDS), set())+class TestVerifyTeamMetadata(BaseTest):"""Test verify_team_metadata functionality."""diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 99a2ff00fef5..f2c822cace56 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -824,6 +824,10 @@ FLAGS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(cache_name="flags",get_teams_queryset_fn=get_teams_with_flags_queryset,get_team_ids_to_skip_fix_fn=get_team_ids_with_recently_updated_flags,+ # 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).+ refresh_only_fields=["id", "project_id", "organization_id"],)diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex 7b6d1e739727..ab3a86bc66cf 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -703,6 +703,11 @@ def _update_flag_definitions(team: Team | int, ttl: int | None = None) -> bool:# HyperCache management config for warming/verification. Uses the same team-scoping# queryset as flags_cache, giving flag definitions the same ~89% team reduction that# the flags cache already has.+# The refresh builds flag definitions from 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).+_FLAG_DEFINITIONS_REFRESH_ONLY_FIELDS = ["id", "project_id", "organization_id"]+FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(hypercache=flag_definitions_hypercache,update_fn=_update_flag_definitions,@@ -715,6 +720,7 @@ FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(# 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,+ refresh_only_fields=_FLAG_DEFINITIONS_REFRESH_ONLY_FIELDS,)