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(flags): retry hypercache verification batch on dropped db connection (#75371)

posthog[bot]75c0bded8778
diff --git a/posthog/storage/hypercache_verifier.py b/posthog/storage/hypercache_verifier.py
index e3dcc72d386a..98cf8625e052 100644
--- a/posthog/storage/hypercache_verifier.py
+++ b/posthog/storage/hypercache_verifier.py
@@ -11,6 +11,8 @@ from collections.abc import Callable
from dataclasses import dataclass, field
from django.conf import settings
+from django.db import InterfaceError, OperationalError, close_old_connections
+from django.db.models import QuerySet
import structlog
from celery.exceptions import SoftTimeLimitExceeded
@@ -39,6 +41,46 @@ MAX_FIXED_TEAM_IDS_TO_LOG = 10
# Maximum number of per-team fix detail logs emitted at INFO per verification run.
MAX_FIX_DETAIL_INFO_LOGS = 10
+# A verification sweep pages through every team on one long-lived Django connection.
+# Poolers rotate and drop that connection mid-sweep, so the batch fetch retries with a
+# fresh connection rather than throwing away a partially-completed run.
+TEAM_BATCH_FETCH_MAX_ATTEMPTS = 4
+TEAM_BATCH_FETCH_BACKOFF_SECONDS = 1.0
+
+
+class TeamBatchFetchError(Exception):
+ """A team batch could not be fetched after exhausting connection retries."""
+
+
+def _fetch_team_batch(base_qs: QuerySet[Team], last_id: int, chunk_size: int) -> list[Team]:
+ """Fetch the next page of teams, reconnecting to Postgres on a dropped connection.
+
+ Django's ``ensure_connection`` only reconnects when the connection object is
+ ``None``, so a connection psycopg has already closed keeps raising until it is
+ discarded — hence the explicit ``close_old_connections()`` between attempts.
+ """
+ last_error: Exception | None = None
+
+ for attempt in range(1, TEAM_BATCH_FETCH_MAX_ATTEMPTS + 1):
+ try:
+ return list(base_qs.filter(id__gt=last_id)[:chunk_size])
+ except (OperationalError, InterfaceError) as e:
+ last_error = e
+ if attempt == TEAM_BATCH_FETCH_MAX_ATTEMPTS:
+ break
+ logger.warning(
+ "Team batch fetch failed, reconnecting and retrying",
+ last_team_id=last_id,
+ attempt=attempt,
+ error=str(e),
+ )
+ close_old_connections()
+ time.sleep(TEAM_BATCH_FETCH_BACKOFF_SECONDS * 2 ** (attempt - 1))
+
+ raise TeamBatchFetchError(
+ f"Failed to fetch team batch after {TEAM_BATCH_FETCH_MAX_ATTEMPTS} attempts (last_team_id={last_id})"
+ ) from last_error
+
@dataclass
class VerificationResult:
@@ -124,7 +166,7 @@ def verify_and_fix_all_teams(
batch_number = 0
while True:
- teams = list(base_qs.filter(id__gt=last_id)[:chunk_size])
+ teams = _fetch_team_batch(base_qs, last_id, chunk_size)
if not teams:
break
diff --git a/posthog/storage/test/test_hypercache_verifier.py b/posthog/storage/test/test_hypercache_verifier.py
index cdf2681aac22..bd5f97f1e462 100644
--- a/posthog/storage/test/test_hypercache_verifier.py
+++ b/posthog/storage/test/test_hypercache_verifier.py
@@ -13,8 +13,9 @@ from functools import partial
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, call, patch
+from django.db import InterfaceError, OperationalError
from django.db.models import QuerySet
-from django.test import TestCase, override_settings
+from django.test import SimpleTestCase, TestCase, override_settings
from celery.exceptions import SoftTimeLimitExceeded
from parameterized import parameterized
@@ -23,7 +24,10 @@ from posthog.models.team.team import Team
from posthog.storage.hypercache_manager import HyperCacheManagementConfig
from posthog.storage.hypercache_verifier import (
MAX_FIXED_TEAM_IDS_TO_LOG,
+ TEAM_BATCH_FETCH_MAX_ATTEMPTS,
+ TeamBatchFetchError,
VerificationResult,
+ _fetch_team_batch,
_fix_and_record,
_verify_and_fix_batch,
verify_and_fix_all_teams,
@@ -1139,3 +1143,60 @@ class TestVerifyAndFixAllTeamsQuerysetScoping(BaseTest):
# Should have verified at least self.team
assert result.total >= 1
+
+
+class _FlakyTeamQuerySet:
+ """Fake queryset that raises the given errors before yielding teams, mimicking a
+ connection dropped by the pooler mid-sweep."""
+
+ def __init__(self, errors: list[Exception], teams: list[Team]) -> None:
+ self.errors = errors
+ self.teams = teams
+ self.requested_after_ids: list[int] = []
+
+ def filter(self, **kwargs) -> "_FlakyTeamQuerySet":
+ self.requested_after_ids.append(kwargs["id__gt"])
+ return self
+
+ def __getitem__(self, _key) -> list[Team]:
+ if self.errors:
+ raise self.errors.pop(0)
+ return self.teams
+
+
+class TestFetchTeamBatch(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("connect_refused", OperationalError("connection timeout expired")),
+ ("connection_closed", InterfaceError("the connection is closed")),
+ ]
+ )
+ def test_reconnects_and_resumes_from_last_id(self, _name, error):
+ team = Team(id=7)
+ base_qs = _FlakyTeamQuerySet([error], [team])
+
+ with (
+ patch("posthog.storage.hypercache_verifier.close_old_connections") as mock_close,
+ patch("posthog.storage.hypercache_verifier.time.sleep"),
+ ):
+ teams = _fetch_team_batch(base_qs, last_id=3, chunk_size=10) # type: ignore[arg-type]
+
+ assert teams == [team]
+ mock_close.assert_called_once()
+ # The retry resumes from the same cursor, so no team is skipped.
+ assert base_qs.requested_after_ids == [3, 3]
+
+ def test_raises_team_batch_fetch_error_once_retries_are_exhausted(self):
+ errors: list[Exception] = [
+ OperationalError("too many clients already") for _ in range(TEAM_BATCH_FETCH_MAX_ATTEMPTS)
+ ]
+ base_qs = _FlakyTeamQuerySet(errors, [])
+
+ with (
+ patch("posthog.storage.hypercache_verifier.close_old_connections"),
+ patch("posthog.storage.hypercache_verifier.time.sleep"),
+ self.assertRaises(TeamBatchFetchError),
+ ):
+ _fetch_team_batch(base_qs, last_id=0, chunk_size=10) # type: ignore[arg-type]
+
+ assert len(base_qs.requested_after_ids) == TEAM_BATCH_FETCH_MAX_ATTEMPTS
diff --git a/posthog/tasks/hypercache_verification.py b/posthog/tasks/hypercache_verification.py
index 8bce9d57a59e..550eef12df69 100644
--- a/posthog/tasks/hypercache_verification.py
+++ b/posthog/tasks/hypercache_verification.py
@@ -20,7 +20,7 @@ from celery import shared_task
from celery.exceptions import SoftTimeLimitExceeded
from posthog.exceptions_capture import capture_exception
-from posthog.storage.hypercache_verifier import _run_verification_for_cache
+from posthog.storage.hypercache_verifier import TeamBatchFetchError, _run_verification_for_cache
from posthog.tasks.utils import CeleryQueue, PushGatewayTask
from products.feature_flags.backend.local_evaluation import (
@@ -45,6 +45,17 @@ FLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS = 30 * 60 # 30 minutes
FLAG_DEFINITIONS_CACHE_TYPE = "flag_definitions"
+def _log_batch_fetch_exhausted(cache_type: str, start_time: float, error: TeamBatchFetchError) -> None:
+ # Not a code failure: Postgres stayed unreachable across retries, so the run
+ # winds down. Unverified teams are picked up on the next scheduled cycle.
+ logger.warning(
+ "Cache verification wound down early, database unreachable",
+ cache_type=cache_type,
+ duration_seconds=time.time() - start_time,
+ error=str(error),
+ )
+
+
def _log_soft_time_limit_exceeded(cache_type: str, start_time: float) -> None:
# Not a failure: the run wound down early because it ran out of time.
# Unverified teams are picked up on the next scheduled cycle.
@@ -86,6 +97,9 @@ def _run_flag_definitions_verification() -> None:
except SoftTimeLimitExceeded:
_log_soft_time_limit_exceeded(FLAG_DEFINITIONS_CACHE_TYPE, start_time)
return
+ except TeamBatchFetchError as e:
+ _log_batch_fetch_exhausted(FLAG_DEFINITIONS_CACHE_TYPE, start_time, e)
+ return
except Exception as e:
logger.exception("Failed cache verification", cache_type=FLAG_DEFINITIONS_CACHE_TYPE, error=str(e))
capture_exception(e)
@@ -143,6 +157,9 @@ def _run_cache_verification(cache_type: CacheType, chunk_size: int) -> None:
except SoftTimeLimitExceeded:
_log_soft_time_limit_exceeded(cache_type, start_time)
return
+ except TeamBatchFetchError as e:
+ _log_batch_fetch_exhausted(cache_type, start_time, e)
+ return
except Exception as e:
logger.exception("Failed cache verification", cache_type=cache_type, error=str(e))
capture_exception(e)
diff --git a/posthog/tasks/test/test_hypercache_verification.py b/posthog/tasks/test/test_hypercache_verification.py
index 0f1e2225b03e..ffc6e290af3d 100644
--- a/posthog/tasks/test/test_hypercache_verification.py
+++ b/posthog/tasks/test/test_hypercache_verification.py
@@ -13,6 +13,7 @@ from django.test import TestCase, override_settings
from celery.exceptions import SoftTimeLimitExceeded
+from posthog.storage.hypercache_verifier import TeamBatchFetchError
from posthog.tasks.hypercache_verification import (
verify_and_fix_flag_definitions_cache_task,
verify_and_fix_flags_cache_task,
@@ -62,6 +63,20 @@ class TestVerifyAndFixFlagsCacheTask(PushGatewayTaskTestMixin, TestCase):
success = self.registry.get_sample_value("posthog_celery_verify_and_fix_flags_cache_task_success")
assert success == 1
+ @patch("posthog.tasks.hypercache_verification.capture_exception")
+ @patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
+ def test_team_batch_fetch_error_winds_down_without_capturing(
+ self, mock_run_verification: MagicMock, mock_capture: MagicMock
+ ) -> None:
+ mock_run_verification.side_effect = TeamBatchFetchError("db unreachable")
+
+ # Should not raise
+ verify_and_fix_flags_cache_task()
+
+ mock_capture.assert_not_called()
+ success = self.registry.get_sample_value("posthog_celery_verify_and_fix_flags_cache_task_success")
+ assert success == 1
+
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_does_not_raise_when_succeeds(self, mock_run_verification: MagicMock) -> None:
mock_run_verification.return_value = MagicMock()
@@ -191,6 +206,20 @@ class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCas
success = self.registry.get_sample_value("posthog_celery_verify_and_fix_flag_definitions_cache_task_success")
assert success == 1
+ @patch("posthog.tasks.hypercache_verification.capture_exception")
+ @patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
+ def test_team_batch_fetch_error_winds_down_without_capturing(
+ self, mock_run_verification: MagicMock, mock_capture: MagicMock
+ ) -> None:
+ mock_run_verification.side_effect = TeamBatchFetchError("db unreachable")
+
+ # Should not raise
+ verify_and_fix_flag_definitions_cache_task()
+
+ mock_capture.assert_not_called()
+ success = self.registry.get_sample_value("posthog_celery_verify_and_fix_flag_definitions_cache_task_success")
+ assert success == 1
+
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_releases_lock_after_error(self, mock_run_verification: MagicMock) -> None:
from django.core.cache import cache as django_cache