: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): let SoftTimeLimitExceeded propagate in cache verification (#67971)
Phil Haack7137730e62f8
diff --git a/posthog/storage/hypercache_verifier.py b/posthog/storage/hypercache_verifier.pyindex 4c2dd9c26910..38325378bc6f 100644--- a/posthog/storage/hypercache_verifier.py+++ b/posthog/storage/hypercache_verifier.py@@ -13,6 +13,7 @@ from dataclasses import dataclass, fieldfrom django.conf import settingsimport structlog+from celery.exceptions import SoftTimeLimitExceededfrom prometheus_client import Counterfrom posthog.models.team.team import Team@@ -187,6 +188,8 @@ def _verify_and_fix_batch(# Batch-read cached values using MGET (single Redis round trip)try:cache_batch_data = config.hypercache.batch_get_from_cache(teams)+ except SoftTimeLimitExceeded:+ raiseexcept Exception as e:logger.warning("Batch cache read failed, falling back to individual lookups", error=str(e))cache_batch_data = {}@@ -200,6 +203,8 @@ def _verify_and_fix_batch(if config.get_team_ids_to_skip_fix_fn:try:team_ids_to_skip_fix = config.get_team_ids_to_skip_fix_fn([t.id for t in teams])+ except SoftTimeLimitExceeded:+ raiseexcept Exception as e:logger.warning("Batch skip-fix check failed, proceeding without skips", error=str(e))@@ -215,6 +220,8 @@ def _verify_and_fix_batch(team_count=len(teams),duration_seconds=time.time() - batch_load_start,)+ except SoftTimeLimitExceeded:+ raiseexcept Exception as e:logger.warning("Batch load failed, falling back to individual loads", error=str(e))@@ -223,6 +230,11 @@ def _verify_and_fix_batch(try:verification = verify_team_fn(team, db_batch_data, cache_batch_data)+ except SoftTimeLimitExceeded:+ # The task ran out of time, not the verify call. Let it propagate so the+ # run winds down instead of looping through the remaining teams; this+ # team is re-verified on the next cycle.+ raiseexcept Exception as e:result.errors += 1logger.exception("Error verifying team", team_id=team.id, error=str(e))@@ -323,6 +335,11 @@ def _fix_and_record(success = Trueelse:success = config.update_fn(team)+ except SoftTimeLimitExceeded:+ # The task ran out of time mid-write, not a cache/storage failure. Let it+ # propagate so the run winds down instead of logging a misleading error and+ # continuing; this team is re-fixed on the next cycle.+ raiseexcept Exception as e:success = Falselogger.exception("Error fixing cache", team_id=team.id, issue_type=issue_type, error=str(e))diff --git a/posthog/storage/test/test_hypercache_verifier.py b/posthog/storage/test/test_hypercache_verifier.pyindex 1a72663aa837..99e1754e6263 100644--- a/posthog/storage/test/test_hypercache_verifier.py+++ b/posthog/storage/test/test_hypercache_verifier.py@@ -13,6 +13,7 @@ from unittest.mock import MagicMock, patchfrom django.test import TestCase, override_settings+from celery.exceptions import SoftTimeLimitExceededfrom parameterized import parameterizedfrom posthog.models.team.team import Team@@ -287,6 +288,41 @@ class TestFixAndRecord(BaseTest):assert result.cache_miss_fixed == 0assert result.fix_failed == 1+ @parameterized.expand(+ [+ ("update_fn", False),+ ("set_cache_value", True),+ ]+ )+ def test_soft_time_limit_exceeded_propagates_instead_of_failing_fix(self, _name, use_db_data):+ """SoftTimeLimitExceeded must propagate so the task winds down cleanly,+ instead of being recorded as a fix failure like a real cache error (which+ previously happened because it subclasses Exception)."""+ mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guard++ verification: dict = {"status": "miss"}+ if use_db_data:+ verification["db_data"] = {"flags": ["flag1"]}+ mock_config.hypercache.set_cache_value.side_effect = SoftTimeLimitExceeded()+ else:+ mock_config.update_fn.side_effect = SoftTimeLimitExceeded()++ result = VerificationResult()++ with self.assertRaises(SoftTimeLimitExceeded):+ _fix_and_record(+ team=self.team,+ config=mock_config,+ issue_type="cache_miss",+ cache_type="test_cache",+ result=result,+ verification=verification,+ )++ assert result.fix_failed == 0+ assert result.cache_miss_fixed == 0+@override_settings(FLAGS_REDIS_URL="redis://test")class TestVerifyAndFixBatch(BaseTest):@@ -453,6 +489,79 @@ class TestVerifyAndFixBatch(BaseTest):assert result.errors == 1assert result.total_fixed == 0+ def test_soft_time_limit_exceeded_propagates_and_stops_batch(self):+ """SoftTimeLimitExceeded from verify_team_fn must propagate so the run winds+ down, instead of being counted as a verification error and continuing on to+ the next team in the batch (which previously happened because it subclasses+ Exception)."""+ mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guard+ mock_config.hypercache.batch_load_fn = None+ mock_config.hypercache.batch_get_from_cache.return_value = {}++ other_team = Team.objects.create(organization=self.organization, name="Other Team")+ processed_team_ids: list[int] = []++ def verify_fn(team, db_batch_data, cache_batch_data):+ processed_team_ids.append(team.id)+ if team.id == self.team.id:+ raise SoftTimeLimitExceeded()+ return {"status": "match", "issue": None}++ result = VerificationResult()++ with patch("posthog.storage.hypercache_verifier.batch_check_expiry_tracking", return_value={}):+ with self.assertRaises(SoftTimeLimitExceeded):+ _verify_and_fix_batch(+ teams=[self.team, other_team],+ config=mock_config,+ verify_team_fn=verify_fn,+ cache_type="test_cache",+ result=result,+ )++ assert result.errors == 0+ assert processed_team_ids == [self.team.id]++ @parameterized.expand(+ [+ ("batch_get_from_cache",),+ ("get_team_ids_to_skip_fix_fn",),+ ("batch_load_fn",),+ ]+ )+ def test_soft_time_limit_exceeded_in_batch_setup_propagates(self, failing_attr):+ """A SoftTimeLimitExceeded from any of the batch-level setup calls (cache+ read, skip-fix check, DB load) must propagate, instead of being logged as a+ routine fallback warning and letting the batch continue toward the per-team+ loop."""+ mock_config = MagicMock()+ mock_config.should_skip_write = None # default: no write guard+ mock_config.hypercache.batch_get_from_cache.return_value = {}+ mock_config.hypercache.batch_load_fn.return_value = {}+ mock_config.get_team_ids_to_skip_fix_fn.return_value = set()+ if failing_attr == "get_team_ids_to_skip_fix_fn":+ mock_config.get_team_ids_to_skip_fix_fn.side_effect = SoftTimeLimitExceeded()+ else:+ getattr(mock_config.hypercache, failing_attr).side_effect = SoftTimeLimitExceeded()++ def verify_fn(team, db_batch_data, cache_batch_data):+ raise AssertionError("Should never reach per-team verification")++ result = VerificationResult()++ with patch("posthog.storage.hypercache_verifier.batch_check_expiry_tracking", return_value={}):+ with self.assertRaises(SoftTimeLimitExceeded):+ _verify_and_fix_batch(+ teams=[self.team],+ config=mock_config,+ verify_team_fn=verify_fn,+ cache_type="test_cache",+ result=result,+ )++ assert result.total == 0+def test_batch_load_fn_called_when_available(self) -> None:mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guarddiff --git a/posthog/tasks/hypercache_verification.py b/posthog/tasks/hypercache_verification.pyindex ada0890b6052..1404d8acddba 100644--- a/posthog/tasks/hypercache_verification.py+++ b/posthog/tasks/hypercache_verification.py@@ -18,6 +18,7 @@ from django.core.cache import cache as django_cacheimport structlogfrom celery import shared_task+from celery.exceptions import SoftTimeLimitExceededfrom posthog.exceptions_capture import capture_exceptionfrom posthog.storage.hypercache_manager import HyperCacheManagementConfig@@ -46,6 +47,16 @@ LOCK_TIMEOUT_SECONDS = 25 * 60 # 25 minutesFLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS = 30 * 60 # 30 minutes+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.+ logger.warning(+ "Cache verification wound down early, time limit reached",+ cache_type=cache_type,+ duration_seconds=time.time() - start_time,+ )++def _run_flag_definitions_verification(config: HyperCacheManagementConfig,include_cohorts: bool,@@ -81,6 +92,9 @@ def _run_flag_definitions_verification(cache_type=cache_type,chunk_size=settings.FLAGS_CACHE_VERIFICATION_CHUNK_SIZE,)+ except SoftTimeLimitExceeded:+ _log_soft_time_limit_exceeded(cache_type, start_time)+ returnexcept Exception as e:logger.exception("Failed cache verification", cache_type=cache_type, error=str(e))capture_exception(e)@@ -135,6 +149,9 @@ def _run_cache_verification(cache_type: CacheType, chunk_size: int) -> None:_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)+ returnexcept 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.pyindex 82a942a0cc03..37cca7d2c1d0 100644--- a/posthog/tasks/test/test_hypercache_verification.py+++ b/posthog/tasks/test/test_hypercache_verification.py@@ -13,6 +13,7 @@ from unittest.mock import MagicMock, patchfrom django.test import TestCase, override_settings+from celery.exceptions import SoftTimeLimitExceededfrom parameterized import parameterizedfrom posthog.tasks.hypercache_verification import (@@ -48,6 +49,23 @@ class TestVerifyAndFixFlagsCacheTask(PushGatewayTaskTestMixin, TestCase):mock_capture.assert_called_once_with(error)assert context.exception is error+ @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+ ) -> 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._run_verification_for_cache")def test_does_not_raise_when_succeeds(self, mock_run_verification: MagicMock) -> None:mock_run_verification.return_value = MagicMock()@@ -224,6 +242,32 @@ class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCasmock_capture.assert_called_once_with(error)assert context.exception is error+ @parameterized.expand(FLAG_DEFINITIONS_VARIANTS)+ @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,+ _name: str,+ task_fn: Callable[[], None],+ _include_cohorts: bool,+ _cache_type: str,+ _other: str,+ metric_name: str,+ 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+ task_fn()++ mock_capture.assert_not_called()+ success = self.registry.get_sample_value(f"posthog_celery_{metric_name}_success")+ assert success == 1+@parameterized.expand(FLAG_DEFINITIONS_VARIANTS)@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")def test_releases_lock_after_error(