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.

feat(flags): count hypercache verification runs that wind down early (#79218)

Phil Haack7ebf3a6be217
diff --git a/posthog/storage/hypercache_verifier.py b/posthog/storage/hypercache_verifier.py
index 98cf8625e052..d80c59f5214d 100644
--- a/posthog/storage/hypercache_verifier.py
+++ b/posthog/storage/hypercache_verifier.py
@@ -17,12 +17,16 @@ from django.db.models import QuerySet
import structlog
from celery.exceptions import SoftTimeLimitExceeded
from prometheus_client import Counter
+from tenacity import RetryCallState, Retrying, retry_if_exception_type, stop_after_attempt, wait_exponential
from posthog.models.team.team import Team
from posthog.storage.hypercache_manager import HyperCacheManagementConfig, batch_check_expiry_tracking
logger = structlog.get_logger(__name__)
+# Verifies one team's cache: (team, db_batch_data, cache_batch_data) -> dict with "status" and "issue".
+VerifyTeamFn = Callable[[Team, dict | None, dict | None], dict]
+
# Number of batches between progress logs (balance between log spam and visibility)
# With 250 teams/batch and ~238K teams, we have ~950 batches. Logging every 20
# batches gives us ~48 progress logs total.
@@ -57,29 +61,38 @@ def _fetch_team_batch(base_qs: QuerySet[Team], last_id: int, chunk_size: int) ->
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.
+ discarded, hence the explicit ``close_old_connections()`` between attempts.
+
+ The Temporal sibling is ``posthog.temporal.common.utils.retry_on_db_connection_drop``,
+ which retries only once because activities carry an outer retry policy. This Celery
+ sweep has none, so it backs off across attempts and raises ``TeamBatchFetchError``
+ for the task to classify the wind-down.
"""
- 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))
+ def _reconnect_and_log(retry_state: RetryCallState) -> None:
+ error = retry_state.outcome.exception() if retry_state.outcome else None
+ logger.warning(
+ "Team batch fetch failed, reconnecting and retrying",
+ last_team_id=last_id,
+ attempt=retry_state.attempt_number,
+ error=str(error),
+ )
+ close_old_connections()
+
+ fetch_with_retry = Retrying(
+ retry=retry_if_exception_type((OperationalError, InterfaceError)),
+ stop=stop_after_attempt(TEAM_BATCH_FETCH_MAX_ATTEMPTS),
+ wait=wait_exponential(multiplier=TEAM_BATCH_FETCH_BACKOFF_SECONDS, max=10),
+ before_sleep=_reconnect_and_log,
+ reraise=True,
+ )
- raise TeamBatchFetchError(
- f"Failed to fetch team batch after {TEAM_BATCH_FETCH_MAX_ATTEMPTS} attempts (last_team_id={last_id})"
- ) from last_error
+ try:
+ return fetch_with_retry(lambda: list(base_qs.filter(id__gt=last_id)[:chunk_size]))
+ except (OperationalError, InterfaceError) as e:
+ raise TeamBatchFetchError(
+ f"Failed to fetch team batch after {TEAM_BATCH_FETCH_MAX_ATTEMPTS} attempts (last_team_id={last_id})"
+ ) from e
@dataclass
@@ -125,7 +138,7 @@ class VerificationResult:
def verify_and_fix_all_teams(
config: HyperCacheManagementConfig,
- verify_team_fn: Callable[[Team, dict | None, dict | None], dict],
+ verify_team_fn: VerifyTeamFn,
cache_type: str,
chunk_size: int | None = None,
) -> VerificationResult:
@@ -220,7 +233,7 @@ def verify_and_fix_all_teams(
def _verify_and_fix_batch(
teams: list[Team],
config: HyperCacheManagementConfig,
- verify_team_fn: Callable[[Team, dict | None, dict | None], dict],
+ verify_team_fn: VerifyTeamFn,
cache_type: str,
result: VerificationResult,
) -> None:
@@ -414,7 +427,7 @@ def _fix_and_record(
def _run_verification_for_cache(
config: HyperCacheManagementConfig,
- verify_team_fn: Callable[[Team, dict | None, dict | None], dict],
+ verify_team_fn: VerifyTeamFn,
cache_type: str,
chunk_size: int,
) -> VerificationResult:
diff --git a/posthog/storage/test/test_hypercache_verifier.py b/posthog/storage/test/test_hypercache_verifier.py
index bd5f97f1e462..969808502e2c 100644
--- a/posthog/storage/test/test_hypercache_verifier.py
+++ b/posthog/storage/test/test_hypercache_verifier.py
@@ -1154,8 +1154,11 @@ class _FlakyTeamQuerySet:
self.teams = teams
self.requested_after_ids: list[int] = []
- def filter(self, **kwargs) -> "_FlakyTeamQuerySet":
- self.requested_after_ids.append(kwargs["id__gt"])
+ def filter(self, *, id__gt: int) -> "_FlakyTeamQuerySet":
+ self.requested_after_ids.append(id__gt)
+ return self
+
+ def order_by(self, *_fields: str) -> "_FlakyTeamQuerySet":
return self
def __getitem__(self, _key) -> list[Team]:
@@ -1167,7 +1170,7 @@ class _FlakyTeamQuerySet:
class TestFetchTeamBatch(SimpleTestCase):
@parameterized.expand(
[
- ("connect_refused", OperationalError("connection timeout expired")),
+ ("connection_timeout", OperationalError("connection timeout expired")),
("connection_closed", InterfaceError("the connection is closed")),
]
)
@@ -1200,3 +1203,40 @@ class TestFetchTeamBatch(SimpleTestCase):
_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
+
+ @parameterized.expand(
+ [
+ ("soft_time_limit", SoftTimeLimitExceeded()),
+ ("unexpected_error", ValueError("bad verify data")),
+ ]
+ )
+ def test_non_connection_error_propagates_without_retry_or_wrapping(self, _name, error):
+ base_qs = _FlakyTeamQuerySet([error], [Team(id=7)])
+
+ with (
+ patch("posthog.storage.hypercache_verifier.close_old_connections") as mock_close,
+ patch("posthog.storage.hypercache_verifier.time.sleep"),
+ self.assertRaises(type(error)),
+ ):
+ _fetch_team_batch(base_qs, last_id=0, chunk_size=10) # type: ignore[arg-type]
+
+ assert base_qs.requested_after_ids == [0]
+ mock_close.assert_not_called()
+
+ def test_sweep_aborts_when_batch_fetch_retries_are_exhausted(self):
+ errors: list[Exception] = [OperationalError("connection dropped") for _ in range(TEAM_BATCH_FETCH_MAX_ATTEMPTS)]
+ flaky_qs = _FlakyTeamQuerySet(errors, [])
+ config = MagicMock()
+ config.narrow_team_queryset.return_value = flaky_qs
+
+ with (
+ patch("posthog.storage.hypercache_verifier.close_old_connections"),
+ patch("posthog.storage.hypercache_verifier.time.sleep"),
+ self.assertRaises(TeamBatchFetchError),
+ ):
+ verify_and_fix_all_teams(
+ config=config,
+ verify_team_fn=lambda team, db, cached: {"status": "match", "issue": None},
+ cache_type="test_cache",
+ chunk_size=10,
+ )
diff --git a/posthog/tasks/hypercache_verification.py b/posthog/tasks/hypercache_verification.py
index 550eef12df69..c46c8d33bd2c 100644
--- a/posthog/tasks/hypercache_verification.py
+++ b/posthog/tasks/hypercache_verification.py
@@ -10,7 +10,7 @@ Provides separate tasks for verifying and fixing each HyperCache-backed cache
"""
import time
-from typing import Literal
+from typing import Literal, get_args
from django.conf import settings
from django.core.cache import cache as django_cache
@@ -18,9 +18,11 @@ from django.core.cache import cache as django_cache
import structlog
from celery import shared_task
from celery.exceptions import SoftTimeLimitExceeded
+from prometheus_client import Counter
from posthog.exceptions_capture import capture_exception
-from posthog.storage.hypercache_verifier import TeamBatchFetchError, _run_verification_for_cache
+from posthog.storage.hypercache_manager import HyperCacheManagementConfig
+from posthog.storage.hypercache_verifier import TeamBatchFetchError, VerifyTeamFn, _run_verification_for_cache
from posthog.tasks.utils import CeleryQueue, PushGatewayTask
from products.feature_flags.backend.local_evaluation import (
@@ -44,6 +46,29 @@ FLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS = 30 * 60 # 30 minutes
FLAG_DEFINITIONS_CACHE_TYPE = "flag_definitions"
+# reason="soft_time_limit" is expected wind-down (the run used up its time budget) and
+# is recorded for observability only; "db_unreachable" and "error" drive the
+# FlagsCacheVerificationRepeatedGiveUps alert in PostHog/charts.
+IncompleteRunReason = Literal["db_unreachable", "error", "soft_time_limit"]
+
+# Verification runs that wound down before completing their sweep, by reason.
+HYPERCACHE_VERIFICATION_INCOMPLETE_RUNS_COUNTER = Counter(
+ "posthog_hypercache_verification_incomplete_runs_total",
+ "Hypercache verification runs that wound down before completing the sweep",
+ labelnames=["cache_type", "reason"],
+)
+
+# Pre-create every label pair so zero-valued series exist from worker boot: increase()
+# never misses a series' first increment, and alert expressions can be validated
+# against live series before any incident occurs.
+for _cache_type in (*get_args(CacheType), FLAG_DEFINITIONS_CACHE_TYPE):
+ for _reason in get_args(IncompleteRunReason):
+ HYPERCACHE_VERIFICATION_INCOMPLETE_RUNS_COUNTER.labels(cache_type=_cache_type, reason=_reason)
+
+
+def _record_incomplete_run(cache_type: str, reason: IncompleteRunReason) -> None:
+ HYPERCACHE_VERIFICATION_INCOMPLETE_RUNS_COUNTER.labels(cache_type=cache_type, reason=reason).inc()
+
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
@@ -66,6 +91,39 @@ def _log_soft_time_limit_exceeded(cache_type: str, start_time: float) -> None:
)
+def _execute_verification_run(
+ config: HyperCacheManagementConfig,
+ verify_team_fn: VerifyTeamFn,
+ cache_type: str,
+ chunk_size: int,
+) -> None:
+ """Run one verification sweep, classifying early wind-downs vs real failures."""
+ start_time = time.time()
+
+ try:
+ _run_verification_for_cache(
+ config=config,
+ verify_team_fn=verify_team_fn,
+ cache_type=cache_type,
+ chunk_size=chunk_size,
+ )
+ except SoftTimeLimitExceeded:
+ _record_incomplete_run(cache_type, "soft_time_limit")
+ _log_soft_time_limit_exceeded(cache_type, start_time)
+ return
+ except TeamBatchFetchError as e:
+ _record_incomplete_run(cache_type, "db_unreachable")
+ _log_batch_fetch_exhausted(cache_type, start_time, e)
+ return
+ except Exception as e:
+ _record_incomplete_run(cache_type, "error")
+ logger.exception("Failed cache verification", cache_type=cache_type, error=str(e))
+ capture_exception(e)
+ raise
+
+ logger.info("Completed cache verification", cache_type=cache_type, duration_seconds=time.time() - start_time)
+
+
def _run_flag_definitions_verification() -> None:
"""
Run verification for the flag definitions cache.
@@ -85,28 +143,12 @@ def _run_flag_definitions_verification() -> None:
try:
logger.info("Starting cache verification", cache_type=FLAG_DEFINITIONS_CACHE_TYPE)
- start_time = time.time()
-
- try:
- _run_verification_for_cache(
- config=FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
- verify_team_fn=verify_team_flag_definitions,
- cache_type=FLAG_DEFINITIONS_CACHE_TYPE,
- chunk_size=settings.FLAGS_CACHE_VERIFICATION_CHUNK_SIZE,
- )
- 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)
- raise
-
- duration = time.time() - start_time
- logger.info("Completed cache verification", cache_type=FLAG_DEFINITIONS_CACHE_TYPE, duration_seconds=duration)
+ _execute_verification_run(
+ config=FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
+ verify_team_fn=verify_team_flag_definitions,
+ cache_type=FLAG_DEFINITIONS_CACHE_TYPE,
+ chunk_size=settings.FLAGS_CACHE_VERIFICATION_CHUNK_SIZE,
+ )
finally:
django_cache.delete(lock_key)
@@ -148,25 +190,7 @@ def _run_cache_verification(cache_type: CacheType, chunk_size: int) -> None:
verify_team_metadata as verify_fn,
)
- start_time = time.time()
-
- try:
- _run_verification_for_cache(
- config=config, verify_team_fn=verify_fn, cache_type=cache_type, chunk_size=chunk_size
- )
- 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)
- raise
-
- duration = time.time() - start_time
- logger.info("Completed cache verification", cache_type=cache_type, duration_seconds=duration)
+ _execute_verification_run(config=config, verify_team_fn=verify_fn, cache_type=cache_type, chunk_size=chunk_size)
finally:
django_cache.delete(lock_key)
@@ -189,7 +213,8 @@ def verify_and_fix_flags_cache_task(self: PushGatewayTask) -> None:
Expected duration: ~8-10 minutes with 250-team batch size.
- Metrics: posthog_hypercache_verify_fixes_total{cache_type="flags", issue_type="..."}
+ Metrics: posthog_hypercache_verify_fixes_total{cache_type="flags", issue_type="..."},
+ posthog_hypercache_verification_incomplete_runs_total{cache_type="flags", reason="..."}
"""
_run_cache_verification("flags", settings.FLAGS_CACHE_VERIFICATION_CHUNK_SIZE)
@@ -212,7 +237,8 @@ def verify_and_fix_team_metadata_cache_task(self: PushGatewayTask) -> None:
Expected duration: ~3-5 minutes with 1000-team batch size.
- Metrics: posthog_hypercache_verify_fixes_total{cache_type="team_metadata", issue_type="..."}
+ Metrics: posthog_hypercache_verify_fixes_total{cache_type="team_metadata", issue_type="..."},
+ posthog_hypercache_verification_incomplete_runs_total{cache_type="team_metadata", reason="..."}
"""
_run_cache_verification("team_metadata", settings.TEAM_METADATA_CACHE_VERIFICATION_CHUNK_SIZE)
@@ -234,6 +260,7 @@ def verify_and_fix_flag_definitions_cache_task(self: PushGatewayTask) -> None:
Uses a distributed lock to skip execution if a previous run is still in progress.
- Metrics: posthog_hypercache_verify_fixes_total{cache_type="flag_definitions", issue_type="..."}
+ Metrics: posthog_hypercache_verify_fixes_total{cache_type="flag_definitions", issue_type="..."},
+ posthog_hypercache_verification_incomplete_runs_total{cache_type="flag_definitions", reason="..."}
"""
_run_flag_definitions_verification()
diff --git a/posthog/tasks/test/test_hypercache_verification.py b/posthog/tasks/test/test_hypercache_verification.py
index ffc6e290af3d..b2bf930b5d94 100644
--- a/posthog/tasks/test/test_hypercache_verification.py
+++ b/posthog/tasks/test/test_hypercache_verification.py
@@ -9,9 +9,11 @@ Tests cover:
from unittest.mock import MagicMock, patch
-from django.test import TestCase, override_settings
+from django.test import SimpleTestCase, TestCase, override_settings
from celery.exceptions import SoftTimeLimitExceeded
+from parameterized import parameterized
+from prometheus_client import REGISTRY
from posthog.storage.hypercache_verifier import TeamBatchFetchError
from posthog.tasks.hypercache_verification import (
@@ -22,6 +24,30 @@ from posthog.tasks.hypercache_verification import (
from posthog.tasks.test.utils import PushGatewayTaskTestMixin
+def _incomplete_runs(cache_type: str, reason: str) -> float:
+ """Current value of the incomplete-runs counter in the default registry."""
+ return (
+ REGISTRY.get_sample_value(
+ "posthog_hypercache_verification_incomplete_runs_total",
+ {"cache_type": cache_type, "reason": reason},
+ )
+ or 0.0
+ )
+
+
+class TestIncompleteRunsCounterSeries(SimpleTestCase):
+ def test_every_label_pair_is_pre_created_at_import(self) -> None:
+ for cache_type in ("flags", "team_metadata", "flag_definitions"):
+ for reason in ("db_unreachable", "error", "soft_time_limit"):
+ assert (
+ REGISTRY.get_sample_value(
+ "posthog_hypercache_verification_incomplete_runs_total",
+ {"cache_type": cache_type, "reason": reason},
+ )
+ is not None
+ ), f"series not pre-created: cache_type={cache_type}, reason={reason}"
+
+
@override_settings(FLAGS_REDIS_URL="redis://test")
class TestVerifyAndFixFlagsCacheTask(PushGatewayTaskTestMixin, TestCase):
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
@@ -39,36 +65,31 @@ class TestVerifyAndFixFlagsCacheTask(PushGatewayTaskTestMixin, TestCase):
def test_captures_and_reraises_error(self, mock_run_verification: MagicMock, mock_capture: MagicMock) -> None:
error = Exception("flags verification failed")
mock_run_verification.side_effect = error
+ before = _incomplete_runs("flags", "error")
with self.assertRaises(Exception) as context:
verify_and_fix_flags_cache_task()
mock_capture.assert_called_once_with(error)
assert context.exception is error
-
+ assert _incomplete_runs("flags", "error") == before + 1
+
+ @parameterized.expand(
+ [
+ ("soft_time_limit", SoftTimeLimitExceeded()),
+ ("db_unreachable", TeamBatchFetchError("db unreachable")),
+ ]
+ )
@patch("posthog.tasks.hypercache_verification.capture_exception")
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
- def test_soft_time_limit_exceeded_winds_down_without_capturing(
- self, mock_run_verification: MagicMock, mock_capture: MagicMock
+ def test_wind_down_completes_cleanly_without_capturing(
+ self, reason: str, error: Exception, mock_run_verification: MagicMock, mock_capture: MagicMock
) -> None:
- """A run that hits the soft time limit winds down cleanly: unlike a real
- verification failure, it is not captured as an error or re-raised, and the
- task's success metric reflects a clean finish."""
- mock_run_verification.side_effect = SoftTimeLimitExceeded()
-
- # 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.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")
+ """A run that winds down early (time budget spent, or database unreachable after
+ retries) is not captured as an error or re-raised, and the task's success metric
+ reflects a clean finish."""
+ mock_run_verification.side_effect = error
+ before = _incomplete_runs("flags", reason)
# Should not raise
verify_and_fix_flags_cache_task()
@@ -76,6 +97,7 @@ class TestVerifyAndFixFlagsCacheTask(PushGatewayTaskTestMixin, TestCase):
mock_capture.assert_not_called()
success = self.registry.get_sample_value("posthog_celery_verify_and_fix_flags_cache_task_success")
assert success == 1
+ assert _incomplete_runs("flags", reason) == before + 1
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_does_not_raise_when_succeeds(self, mock_run_verification: MagicMock) -> None:
@@ -124,12 +146,14 @@ class TestVerifyAndFixTeamMetadataCacheTask(PushGatewayTaskTestMixin, TestCase):
def test_captures_and_reraises_error(self, mock_run_verification: MagicMock, mock_capture: MagicMock) -> None:
error = Exception("team_metadata verification failed")
mock_run_verification.side_effect = error
+ before = _incomplete_runs("team_metadata", "error")
with self.assertRaises(Exception) as context:
verify_and_fix_team_metadata_cache_task()
mock_capture.assert_called_once_with(error)
assert context.exception is error
+ assert _incomplete_runs("team_metadata", "error") == before + 1
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_does_not_raise_when_succeeds(self, mock_run_verification: MagicMock) -> None:
@@ -182,36 +206,31 @@ class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCas
def test_captures_and_reraises_error(self, mock_run_verification: MagicMock, mock_capture: MagicMock) -> None:
error = Exception("flag_definitions verification failed")
mock_run_verification.side_effect = error
+ before = _incomplete_runs("flag_definitions", "error")
with self.assertRaises(Exception) as context:
verify_and_fix_flag_definitions_cache_task()
mock_capture.assert_called_once_with(error)
assert context.exception is error
-
+ assert _incomplete_runs("flag_definitions", "error") == before + 1
+
+ @parameterized.expand(
+ [
+ ("soft_time_limit", SoftTimeLimitExceeded()),
+ ("db_unreachable", TeamBatchFetchError("db unreachable")),
+ ]
+ )
@patch("posthog.tasks.hypercache_verification.capture_exception")
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
- def test_soft_time_limit_exceeded_winds_down_without_capturing(
- self, mock_run_verification: MagicMock, mock_capture: MagicMock
+ def test_wind_down_completes_cleanly_without_capturing(
+ self, reason: str, error: Exception, mock_run_verification: MagicMock, mock_capture: MagicMock
) -> None:
- """A run that hits the soft time limit winds down cleanly: unlike a real
- verification failure, it is not captured as an error or re-raised, and the
- task's success metric reflects a clean finish."""
- mock_run_verification.side_effect = SoftTimeLimitExceeded()
-
- # 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.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")
+ """A run that winds down early (time budget spent, or database unreachable after
+ retries) is not captured as an error or re-raised, and the task's success metric
+ reflects a clean finish."""
+ mock_run_verification.side_effect = error
+ before = _incomplete_runs("flag_definitions", reason)
# Should not raise
verify_and_fix_flag_definitions_cache_task()
@@ -219,6 +238,7 @@ class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCas
mock_capture.assert_not_called()
success = self.registry.get_sample_value("posthog_celery_verify_and_fix_flag_definitions_cache_task_success")
assert success == 1
+ assert _incomplete_runs("flag_definitions", reason) == before + 1
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_releases_lock_after_error(self, mock_run_verification: MagicMock) -> None:
diff --git a/posthog/temporal/common/utils.py b/posthog/temporal/common/utils.py
index a31693d04272..ef13350b5930 100644
--- a/posthog/temporal/common/utils.py
+++ b/posthog/temporal/common/utils.py
@@ -190,6 +190,10 @@ def retry_on_db_connection_drop(operation: Callable[[], T]) -> T:
``InterfaceError`` on first use. Evict the dead connection and retry once; a second
failure propagates, left to the caller's retry posture.
+ The single retry leans on the activity's outer Temporal retry policy. Code without
+ one (e.g. a Celery task) needs multi-attempt backoff instead; see
+ ``posthog.storage.hypercache_verifier._fetch_team_batch``.
+
Pass a zero-arg callable that *produces* the result, so the retry can issue a fresh
query: