Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(hypercache): route CLI team queries through narrow_team_queryset (#71143)

Phil Haackce8cc76ec4e1
diff --git a/posthog/management/commands/_base_hypercache_command.py b/posthog/management/commands/_base_hypercache_command.py
index c95d9f468fd6..d58014ff86d8 100644
--- a/posthog/management/commands/_base_hypercache_command.py
+++ b/posthog/management/commands/_base_hypercache_command.py
@@ -220,7 +220,7 @@ class BaseHyperCacheCommand(BaseCommand):
pass
total = self.process_teams_in_chunks(
- Team.objects.select_related("organization", "project"),
+ self.get_teams_queryset(),
chunk_size=1000,
process_chunk_fn=process_chunk
)
@@ -248,13 +248,22 @@ class BaseHyperCacheCommand(BaseCommand):
# Team scoping
+ # Team columns the commands read beyond the config's refresh_only_fields:
+ # the interactive output prints team.name next to each issue/fix line.
+ COMMAND_EXTRA_TEAM_FIELDS: tuple[str, ...] = ("name",)
+
+ def narrow_team_queryset(self, queryset: QuerySet[Team]) -> QuerySet[Team]:
+ """Narrow a Team queryset via the config, keeping the columns commands print."""
+ return self.get_hypercache_config().narrow_team_queryset(queryset, extra_fields=self.COMMAND_EXTRA_TEAM_FIELDS)
+
def get_teams_queryset(self) -> QuerySet:
"""Return the base queryset of teams to process.
Uses the config's ``get_teams_queryset()`` method when set, falling
- back to all teams.
+ back to all teams. Narrowed so a Team column the read replica hasn't
+ migrated yet can't break the command's SELECT.
"""
- return self.get_hypercache_config().get_teams_queryset().select_related("organization", "project")
+ return self.narrow_team_queryset(self.get_hypercache_config().get_teams_queryset())
def _print_scope_info(self, scoped_count: int, total_count: int):
"""Print a message when team scoping reduces the verification set."""
@@ -313,7 +322,7 @@ class BaseHyperCacheCommand(BaseCommand):
# Process teams in chunks to avoid loading all teams into memory at once
if team_ids:
- teams_queryset = Team.objects.filter(id__in=team_ids).select_related("organization", "project")
+ teams_queryset = self.narrow_team_queryset(Team.objects.filter(id__in=team_ids))
self.stdout.write(f"Verifying {teams_queryset.count()} specific teams...\n")
self._verify_teams_batch(list(teams_queryset), stats, mismatches, verbose, fix)
elif sample_size:
@@ -688,7 +697,7 @@ class BaseHyperCacheCommand(BaseCommand):
"""
self.stdout.write(f"\nWarming {cache_name} cache for {len(team_ids)} specific team(s)...\n")
- teams = list(Team.objects.filter(id__in=team_ids).select_related("organization", "project"))
+ teams = list(self.narrow_team_queryset(Team.objects.filter(id__in=team_ids)))
found_ids = {team.id for team in teams}
missing_ids = set(team_ids) - found_ids
diff --git a/posthog/management/commands/analyze_flags_cache_sizes.py b/posthog/management/commands/analyze_flags_cache_sizes.py
index b9e688b1b7f0..f00ebdc87ff9 100644
--- a/posthog/management/commands/analyze_flags_cache_sizes.py
+++ b/posthog/management/commands/analyze_flags_cache_sizes.py
@@ -47,7 +47,7 @@ class Command(BaseHyperCacheCommand):
return
# Random sample of teams for unbiased statistics
- teams = list(Team.objects.select_related("organization", "project").order_by("?")[:sample_size])
+ teams = list(self.narrow_team_queryset(Team.objects.all()).order_by("?")[:sample_size])
self.stdout.write(f"\nAnalyzing {len(teams)} teams (out of {total_teams} total)...")
diff --git a/posthog/management/commands/analyze_team_cache_sizes.py b/posthog/management/commands/analyze_team_cache_sizes.py
index 52185e599b42..8c6ec59a84b5 100644
--- a/posthog/management/commands/analyze_team_cache_sizes.py
+++ b/posthog/management/commands/analyze_team_cache_sizes.py
@@ -45,7 +45,7 @@ class Command(BaseHyperCacheCommand):
return
# Random sample of teams for unbiased statistics
- teams = list(Team.objects.order_by("?")[:sample_size])
+ teams = list(self.narrow_team_queryset(Team.objects.all()).order_by("?")[:sample_size])
self.stdout.write(f"\nAnalyzing {len(teams)} teams (out of {total_teams} total)...")
diff --git a/posthog/management/commands/test/test_base_hypercache_command.py b/posthog/management/commands/test/test_base_hypercache_command.py
index 115928422238..01091003efd7 100644
--- a/posthog/management/commands/test/test_base_hypercache_command.py
+++ b/posthog/management/commands/test/test_base_hypercache_command.py
@@ -8,6 +8,7 @@ Tests cover:
- Continued processing after individual team errors
"""
+from functools import partial
from io import StringIO
from typing import Any
@@ -119,6 +120,9 @@ def create_mock_config():
mock_config.cache_display_name = "test cache"
mock_config.get_teams_queryset_fn = None # Match real config default
mock_config.get_teams_queryset.return_value = Team.objects.all()
+ # Run narrowing for real so the command gets an actual queryset back
+ mock_config.refresh_only_fields = None
+ mock_config.narrow_team_queryset.side_effect = partial(HyperCacheManagementConfig.narrow_team_queryset, mock_config)
return mock_config
diff --git a/posthog/storage/hypercache_manager.py b/posthog/storage/hypercache_manager.py
index f8c5e5bd89df..c7e0de466554 100644
--- a/posthog/storage/hypercache_manager.py
+++ b/posthog/storage/hypercache_manager.py
@@ -278,18 +278,24 @@ class HyperCacheManagementConfig:
return self.get_teams_queryset_fn()
return Team.objects.all()
- def narrow_team_queryset(self, queryset: "QuerySet[Team]") -> "QuerySet[Team]":
+ def narrow_team_queryset(
+ self, queryset: "QuerySet[Team]", *, extra_fields: tuple[str, ...] = ()
+ ) -> "QuerySet[Team]":
"""Select related org/project and restrict Team columns to refresh_only_fields.
- The library warm, refresh, and verify paths route through this so a Team
- column the read replica hasn't migrated yet can't turn their `SELECT *`
- into an UndefinedColumn error (see the refresh_only_fields field comment).
- Only Team columns are narrowed: org/project rows are still fully selected,
- and the management-command paths don't route through here yet.
+ The library warm, refresh, and verify paths and the management commands all
+ route through this so a Team column the read replica hasn't migrated yet
+ can't turn their `SELECT *` into an UndefinedColumn error (see the
+ refresh_only_fields field comment). Only Team columns are narrowed:
+ org/project rows are still fully selected.
+
+ extra_fields adds Team columns a caller needs beyond refresh_only_fields
+ (e.g. the management commands print team.name) without widening the hot
+ cron SELECTs for every config.
"""
queryset = queryset.select_related("organization", "project")
if self.refresh_only_fields is not None:
- queryset = queryset.only(*self.refresh_only_fields)
+ queryset = queryset.only(*self.refresh_only_fields, *extra_fields)
return queryset
diff --git a/posthog/storage/test/test_hypercache_manager.py b/posthog/storage/test/test_hypercache_manager.py
index ebe091bca050..39b75d98f880 100644
--- a/posthog/storage/test/test_hypercache_manager.py
+++ b/posthog/storage/test/test_hypercache_manager.py
@@ -12,6 +12,7 @@ from unittest.mock import MagicMock, patch
from prometheus_client import CollectorRegistry
+from posthog.models.team.team import Team
from posthog.storage.hypercache import HyperCache
from posthog.storage.hypercache_manager import (
HyperCacheManagementConfig,
@@ -667,3 +668,22 @@ class TestWarmCachesQuerysetScoping(BaseTest):
warm_caches(config, batch_size=100, stagger_ttl=False, team_ids=[self.team.id])
assert self.team.id in warmed_team_ids
+
+
+class TestNarrowTeamQueryset(BaseTest):
+ def test_extra_fields_are_selected_alongside_refresh_fields(self):
+ config = HyperCacheManagementConfig(
+ hypercache=create_test_hypercache(),
+ update_fn=lambda team, ttl=None: True,
+ cache_name="test_cache",
+ refresh_only_fields=["id", "project_id", "organization_id"],
+ )
+
+ team = config.narrow_team_queryset(Team.objects.filter(id=self.team.id), extra_fields=("name",)).get()
+
+ deferred = team.get_deferred_fields()
+ # Columns outside the refresh set stay deferred — a SELECT * regression leaves this empty.
+ assert deferred
+ # Neither the refresh fields nor the extra fields are deferred, so reading
+ # team.name never triggers a per-team lazy load.
+ assert deferred & {"id", "project_id", "organization_id", "name"} == set()