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): wind down hypercache verification before the hard time limit (#87131)

Phil Haack341525df61e4
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.md
index f2f8a21d5ed7..b18cc81f5ec1 100644
--- a/docs/internal/feature-flags/hypercache-system.md
+++ b/docs/internal/feature-flags/hypercache-system.md
@@ -397,7 +397,10 @@ The flag definitions verification task (runs hourly at :50) compares cached flag
4. Auto-fixes mismatches by refreshing the cache
5. Reports metrics on match/mismatch/miss rates
-The task has a 25-minute soft / 30-minute hard time limit.
+The task has a 35-minute soft / 40-minute hard time limit.
+It winds down at a batch boundary two minutes before the soft limit,
+recording the partial run under `reason="deadline"` in `posthog_hypercache_verification_incomplete_runs_total`;
+the next run restarts from the first team.
Configuration:
diff --git a/posthog/storage/hypercache_verifier.py b/posthog/storage/hypercache_verifier.py
index d80c59f5214d..5b18ce542218 100644
--- a/posthog/storage/hypercache_verifier.py
+++ b/posthog/storage/hypercache_verifier.py
@@ -95,7 +95,7 @@ def _fetch_team_batch(base_qs: QuerySet[Team], last_id: int, chunk_size: int) ->
) from e
-@dataclass
+@dataclass(frozen=False)
class VerificationResult:
"""Result of verifying all teams' caches."""
@@ -110,6 +110,10 @@ class VerificationResult:
skipped_team_ids: list[int] = field(default_factory=list)
# Per-run logging cap state, not a verification outcome.
fix_detail_info_logs_emitted: int = 0
+ # True when the sweep hit its monotonic deadline and wound down before
+ # covering every team, so the caller can record the wind-down. Per-run state,
+ # not a verification outcome.
+ wound_down_early: bool = False
@property
def total_fixed(self) -> int:
@@ -141,6 +145,8 @@ def verify_and_fix_all_teams(
verify_team_fn: VerifyTeamFn,
cache_type: str,
chunk_size: int | None = None,
+ *,
+ stop_time: float | None = None,
) -> VerificationResult:
"""
Verify caches for teams in the configured scope and auto-fix any issues.
@@ -159,6 +165,9 @@ def verify_and_fix_all_teams(
cache_type: Name for metrics/logging (e.g., "team_metadata", "flags")
chunk_size: Number of teams to process per batch. Defaults to
settings.FLAGS_CACHE_VERIFICATION_CHUNK_SIZE (the more conservative setting).
+ stop_time: Monotonic deadline (from ``time.monotonic()``). When set, the sweep
+ winds down at the first batch boundary past it, returning a partial result
+ instead of running until Celery's hard time limit SIGKILLs the worker.
Returns:
VerificationResult with stats and list of fixed team IDs
@@ -219,6 +228,24 @@ def verify_and_fix_all_teams(
last_team_id=teams[-1].id,
)
+ # Wind down at a batch boundary once the deadline passes, so the run ends
+ # cleanly and records the wind-down instead of being SIGKILLed mid-batch past
+ # the hard time limit (which reports nothing). The cursor is not persisted, so
+ # the next cycle restarts from id 0 rather than resuming here: a run that winds
+ # down repeatedly leaves the same tail of high-id teams unverified until it can
+ # finish within the deadline. Only wind down when teams actually remain: a
+ # deadline that trips on the final batch has already covered every team, so it
+ # completed rather than winding down early.
+ if stop_time is not None and time.monotonic() > stop_time and _fetch_team_batch(base_qs, teams[-1].id, 1):
+ result.wound_down_early = True
+ logger.warning(
+ "Cache verification wound down early, deadline reached",
+ cache_type=cache_type,
+ teams_verified_total=result.total,
+ last_team_id=teams[-1].id,
+ )
+ break
+
last_id = teams[-1].id
# Explicitly release memory between batches to prevent accumulation.
@@ -430,6 +457,7 @@ def _run_verification_for_cache(
verify_team_fn: VerifyTeamFn,
cache_type: str,
chunk_size: int,
+ stop_time: float | None = None,
) -> VerificationResult:
"""
Run verification for a single cache type and log results.
@@ -439,6 +467,8 @@ def _run_verification_for_cache(
verify_team_fn: Function to verify a single team
cache_type: Name for metrics/logging
chunk_size: Number of teams to process per batch
+ stop_time: Monotonic deadline forwarded to verify_and_fix_all_teams for
+ early wind-down.
Returns:
VerificationResult with stats
@@ -451,6 +481,7 @@ def _run_verification_for_cache(
verify_team_fn=verify_team_fn,
cache_type=cache_type,
chunk_size=chunk_size,
+ stop_time=stop_time,
)
duration = time.time() - start_time
diff --git a/posthog/storage/test/test_hypercache_verifier.py b/posthog/storage/test/test_hypercache_verifier.py
index 969808502e2c..d4d40d61cf51 100644
--- a/posthog/storage/test/test_hypercache_verifier.py
+++ b/posthog/storage/test/test_hypercache_verifier.py
@@ -8,6 +8,7 @@ Tests cover:
- Error handling and edge cases
"""
+import time
from functools import partial
from posthog.test.base import BaseTest
@@ -1145,6 +1146,41 @@ class TestVerifyAndFixAllTeamsQuerysetScoping(BaseTest):
assert result.total >= 1
+@override_settings(FLAGS_REDIS_URL="redis://test")
+class TestVerifyAndFixAllTeamsDeadline(BaseTest):
+ @parameterized.expand(
+ [
+ # A passed deadline breaks after the first (chunk_size=1) batch, leaving the
+ # second team for the next cycle; headroom processes both teams.
+ ("deadline_passed", 1, -1.0, True, 1),
+ ("headroom", 1, 3600.0, False, 2),
+ # Both teams fit in one batch, so nothing remains when the deadline trips on it:
+ # the sweep completed and must not record a false early wind-down.
+ ("deadline_passed_final_batch", 2, -1.0, False, 2),
+ ]
+ )
+ def test_winds_down_at_batch_boundary_once_deadline_passes(
+ self, _name: str, chunk_size: int, stop_time_offset: float, expected_wound_down: bool, expected_total: int
+ ) -> None:
+ team2 = Team.objects.create(organization=self.organization, name="Team 2")
+ mock_config = _make_verifier_config(Team.objects.filter(id__in=[self.team.id, team2.id]))
+
+ def verify_fn(team, db_batch_data, cache_batch_data):
+ return {"status": "match", "issue": None}
+
+ with patch("posthog.storage.hypercache_verifier.batch_check_expiry_tracking", return_value={}):
+ result = verify_and_fix_all_teams(
+ config=mock_config,
+ verify_team_fn=verify_fn,
+ cache_type="test_cache",
+ chunk_size=chunk_size,
+ stop_time=time.monotonic() + stop_time_offset,
+ )
+
+ assert result.wound_down_early is expected_wound_down
+ assert result.total == expected_total
+
+
class _FlakyTeamQuerySet:
"""Fake queryset that raises the given errors before yielding teams, mimicking a
connection dropped by the pooler mid-sweep."""
diff --git a/posthog/tasks/hypercache_verification.py b/posthog/tasks/hypercache_verification.py
index 57aee230019d..fe6b2d4a0fb4 100644
--- a/posthog/tasks/hypercache_verification.py
+++ b/posthog/tasks/hypercache_verification.py
@@ -39,22 +39,29 @@ logger = structlog.get_logger(__name__)
CacheType = Literal["flags", "team_metadata"]
-# Lock timeout matches time_limit to ensure lock is released if task is killed.
-# With 30-minute scheduling and 25-minute lock timeout, a crashed task's lock
-# expires before the next scheduled run, so at most 1 run is skipped after a crash.
-LOCK_TIMEOUT_SECONDS = 25 * 60 # 25 minutes
-
-# Flag definitions verification lock timeout matches time_limit (30 min) to ensure
-# the lock expires before the next scheduled run if a task crashes without executing
-# its finally block, guaranteeing at most 1 run is skipped after a crash.
-FLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS = 30 * 60 # 30 minutes
+# Each task locks for its own hard time limit, passed in as ``self.time_limit``. A
+# crashed task that never runs its finally block still releases the lock when the
+# timeout expires. The timeout is measured from lock acquisition, and every task's
+# hard limit is <= its schedule interval, so under on-time scheduling that expiry
+# lands before the next scheduled run and a crash skips no runs. A run that starts
+# late enough for its lock to outlive the next tick skips at most one run.
+
+# Wind the sweep down this long before the soft time limit, so the batch-boundary
+# deadline check trips before Celery's SoftTimeLimitExceeded can fire mid-batch. Must
+# exceed one batch's processing time (1-3s in prod); 2 minutes leaves wide margin
+# while giving up little of the time budget.
+DEADLINE_HEADROOM_SECONDS = 2 * 60
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"]
+# Both "deadline" and "soft_time_limit" are expected wind-downs recorded for
+# observability only. "deadline" is the graceful path: the sweep hit its own
+# monotonic deadline and stopped at a batch boundary — the healthy steady state.
+# "soft_time_limit" means Celery's soft-limit signal fired first, so the deadline
+# was too loose to wind down in time; a rise here says the budget needs tuning.
+# "db_unreachable" and "error" drive the FlagsCacheVerificationRepeatedGiveUps
+# alert in PostHog/charts.
+IncompleteRunReason = Literal["db_unreachable", "error", "soft_time_limit", "deadline"]
# Verification runs that wound down before completing their sweep, by reason.
HYPERCACHE_VERIFICATION_INCOMPLETE_RUNS_COUNTER = Counter(
@@ -101,16 +108,25 @@ def _execute_verification_run(
verify_team_fn: VerifyTeamFn,
cache_type: str,
chunk_size: int,
+ soft_limit_seconds: float,
) -> None:
- """Run one verification sweep, classifying early wind-downs vs real failures."""
+ """Run one verification sweep, classifying early wind-downs vs real failures.
+
+ The sweep gets a monotonic deadline ``DEADLINE_HEADROOM_SECONDS`` before the soft
+ time limit, so it winds down at a batch boundary and reports the deferral before
+ Celery's SoftTimeLimitExceeded fires mid-batch (recorded as ``soft_time_limit``)
+ or the hard time limit SIGKILLs the worker (which reports nothing).
+ """
start_time = time.time()
+ stop_time = time.monotonic() + max(soft_limit_seconds - DEADLINE_HEADROOM_SECONDS, 0)
try:
- _run_verification_for_cache(
+ result = _run_verification_for_cache(
config=config,
verify_team_fn=verify_team_fn,
cache_type=cache_type,
chunk_size=chunk_size,
+ stop_time=stop_time,
)
except SoftTimeLimitExceeded:
_record_incomplete_run(cache_type, "soft_time_limit")
@@ -126,10 +142,16 @@ def _execute_verification_run(
capture_exception(e)
raise
+ # A deadline wind-down returns normally (no SoftTimeLimitExceeded raised). Record it
+ # under its own reason so the metric distinguishes the graceful path from Celery's
+ # soft-limit firing first (which means the deadline was too loose).
+ if result.wound_down_early:
+ _record_incomplete_run(cache_type, "deadline")
+
logger.info("Completed cache verification", cache_type=cache_type, duration_seconds=time.time() - start_time)
-def _run_flag_definitions_verification() -> None:
+def _run_flag_definitions_verification(soft_limit_seconds: float, lock_timeout_seconds: float) -> None:
"""
Run verification for the flag definitions cache.
@@ -142,7 +164,7 @@ def _run_flag_definitions_verification() -> None:
"""
lock_key = f"posthog:hypercache_verification:{FLAG_DEFINITIONS_CACHE_TYPE}:lock"
- if not django_cache.add(lock_key, "locked", timeout=FLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS):
+ if not django_cache.add(lock_key, "locked", timeout=lock_timeout_seconds):
logger.info("Skipping cache verification - already running", cache_type=FLAG_DEFINITIONS_CACHE_TYPE)
return
@@ -153,12 +175,15 @@ def _run_flag_definitions_verification() -> None:
verify_team_fn=verify_team_flag_definitions,
cache_type=FLAG_DEFINITIONS_CACHE_TYPE,
chunk_size=settings.FLAGS_CACHE_VERIFICATION_CHUNK_SIZE,
+ soft_limit_seconds=soft_limit_seconds,
)
finally:
django_cache.delete(lock_key)
-def _run_cache_verification(cache_type: CacheType, chunk_size: int) -> None:
+def _run_cache_verification(
+ cache_type: CacheType, chunk_size: int, soft_limit_seconds: float, lock_timeout_seconds: float
+) -> None:
"""
Run verification for a specific cache type.
@@ -176,7 +201,7 @@ def _run_cache_verification(cache_type: CacheType, chunk_size: int) -> None:
lock_key = f"posthog:hypercache_verification:{cache_type}:lock"
# Attempt to acquire lock - cache.add returns False if key already exists
- if not django_cache.add(lock_key, "locked", timeout=LOCK_TIMEOUT_SECONDS):
+ if not django_cache.add(lock_key, "locked", timeout=lock_timeout_seconds):
logger.info("Skipping cache verification - already running", cache_type=cache_type)
return
@@ -195,7 +220,13 @@ def _run_cache_verification(cache_type: CacheType, chunk_size: int) -> None:
verify_team_metadata as verify_fn,
)
- _execute_verification_run(config=config, verify_team_fn=verify_fn, cache_type=cache_type, chunk_size=chunk_size)
+ _execute_verification_run(
+ config=config,
+ verify_team_fn=verify_fn,
+ cache_type=cache_type,
+ chunk_size=chunk_size,
+ soft_limit_seconds=soft_limit_seconds,
+ )
finally:
django_cache.delete(lock_key)
@@ -206,8 +237,8 @@ def _run_cache_verification(cache_type: CacheType, chunk_size: int) -> None:
ignore_result=True,
name=VERIFY_FLAGS_CACHE_TASK_NAME,
queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,
- soft_time_limit=20 * 60, # 20 min soft limit
- time_limit=25 * 60, # 25 min hard limit (matches LOCK_TIMEOUT_SECONDS)
+ soft_time_limit=25 * 60, # 25 min soft limit
+ time_limit=28 * 60, # 28 min hard limit (< the 30 min schedule; also the lock timeout)
)
def verify_and_fix_flags_cache_task(self: PushGatewayTask) -> None:
"""
@@ -217,12 +248,15 @@ def verify_and_fix_flags_cache_task(self: PushGatewayTask) -> None:
fixing any cache misses, mismatches, or expiry tracking issues.
Uses a distributed lock to skip execution if a previous run is still in progress.
- Expected duration: ~8-10 minutes with 250-team batch size.
+ Expected duration: ~8 minutes (observed 2026-08-21); the hard limit stays under the
+ 30-minute schedule so a run always finishes before the next one is due.
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)
+ _run_cache_verification(
+ "flags", settings.FLAGS_CACHE_VERIFICATION_CHUNK_SIZE, self.soft_time_limit, self.time_limit
+ )
@shared_task(
@@ -231,8 +265,8 @@ def verify_and_fix_flags_cache_task(self: PushGatewayTask) -> None:
ignore_result=True,
name=VERIFY_TEAM_METADATA_CACHE_TASK_NAME,
queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,
- soft_time_limit=20 * 60, # 20 min soft limit
- time_limit=25 * 60, # 25 min hard limit (matches LOCK_TIMEOUT_SECONDS)
+ soft_time_limit=35 * 60, # 35 min soft limit
+ time_limit=40 * 60, # 40 min hard limit (< the hourly schedule; also the lock timeout)
)
def verify_and_fix_team_metadata_cache_task(self: PushGatewayTask) -> None:
"""
@@ -242,12 +276,14 @@ def verify_and_fix_team_metadata_cache_task(self: PushGatewayTask) -> None:
automatically fixing any cache misses, mismatches, or expiry tracking issues.
Uses a distributed lock to skip execution if a previous run is still in progress.
- Expected duration: ~3-5 minutes with 1000-team batch size.
+ Expected duration: ~15-20 minutes (observed 2026-08-19).
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)
+ _run_cache_verification(
+ "team_metadata", settings.TEAM_METADATA_CACHE_VERIFICATION_CHUNK_SIZE, self.soft_time_limit, self.time_limit
+ )
@shared_task(
@@ -256,8 +292,8 @@ def verify_and_fix_team_metadata_cache_task(self: PushGatewayTask) -> None:
ignore_result=True,
name=VERIFY_FLAG_DEFINITIONS_CACHE_TASK_NAME,
queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,
- soft_time_limit=25 * 60, # 25 min soft limit
- time_limit=30 * 60, # 30 min hard limit (matches FLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS)
+ soft_time_limit=35 * 60, # 35 min soft limit
+ time_limit=40 * 60, # 40 min hard limit (< the hourly schedule; also the lock timeout)
)
def verify_and_fix_flag_definitions_cache_task(self: PushGatewayTask) -> None:
"""
@@ -268,7 +304,11 @@ 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.
+ Expected duration: was pinned at its old 30-minute hard limit in prod (observed
+ 2026-08-21), so the budget is now 35/40 min; the sweep still winds down gracefully
+ at the deadline if it runs long, and the every-minute self-heal drain covers gaps.
+
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()
+ _run_flag_definitions_verification(self.soft_time_limit, self.time_limit)
diff --git a/posthog/tasks/test/test_hypercache_verification.py b/posthog/tasks/test/test_hypercache_verification.py
index 13811110d43a..0d4eac1a4cf7 100644
--- a/posthog/tasks/test/test_hypercache_verification.py
+++ b/posthog/tasks/test/test_hypercache_verification.py
@@ -15,8 +15,9 @@ from celery.exceptions import SoftTimeLimitExceeded
from parameterized import parameterized
from prometheus_client import REGISTRY
-from posthog.storage.hypercache_verifier import TeamBatchFetchError
+from posthog.storage.hypercache_verifier import TeamBatchFetchError, VerificationResult
from posthog.tasks.hypercache_verification import (
+ DEADLINE_HEADROOM_SECONDS,
verify_and_fix_flag_definitions_cache_task,
verify_and_fix_flags_cache_task,
verify_and_fix_team_metadata_cache_task,
@@ -39,7 +40,7 @@ def _incomplete_runs(cache_type: str, reason: str) -> float:
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"):
+ for reason in ("db_unreachable", "error", "soft_time_limit", "deadline"):
assert (
REGISTRY.get_sample_value(
"posthog_hypercache_verification_incomplete_runs_total",
@@ -53,7 +54,7 @@ class TestIncompleteRunsCounterSeries(SimpleTestCase):
class TestVerifyAndFixFlagsCacheTask(PushGatewayTaskTestMixin, TestCase):
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_verifies_flags_cache(self, mock_run_verification: MagicMock) -> None:
- mock_run_verification.return_value = MagicMock()
+ mock_run_verification.return_value = VerificationResult()
verify_and_fix_flags_cache_task()
@@ -102,16 +103,54 @@ class TestVerifyAndFixFlagsCacheTask(PushGatewayTaskTestMixin, TestCase):
@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()
+ mock_run_verification.return_value = VerificationResult()
# Should not raise
verify_and_fix_flags_cache_task()
mock_run_verification.assert_called_once()
+ @patch("posthog.tasks.hypercache_verification.time.monotonic", return_value=1000.0)
+ @patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
+ def test_passes_monotonic_deadline_to_sweep(
+ self, mock_run_verification: MagicMock, _mock_monotonic: MagicMock
+ ) -> None:
+ # The sweep's wind-down deadline is the task's soft time limit minus the
+ # headroom, so the batch-boundary check trips before Celery's soft-limit
+ # signal can fire mid-batch.
+ mock_run_verification.return_value = VerificationResult()
+
+ verify_and_fix_flags_cache_task()
+
+ expected = 1000.0 + (verify_and_fix_flags_cache_task.soft_time_limit - DEADLINE_HEADROOM_SECONDS)
+ assert mock_run_verification.call_args.kwargs["stop_time"] == expected
+
+ @patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
+ def test_deadline_winddown_records_incomplete_run_without_raising(self, mock_run_verification: MagicMock) -> None:
+ # A deadline wind-down returns a partial result (no SoftTimeLimitExceeded raised);
+ # it must still be counted as a "deadline" incomplete run, and finish cleanly.
+ mock_run_verification.return_value = VerificationResult(wound_down_early=True)
+ before = _incomplete_runs("flags", "deadline")
+
+ # Should not raise
+ verify_and_fix_flags_cache_task()
+
+ assert _incomplete_runs("flags", "deadline") == before + 1
+ 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_completed_sweep_does_not_record_incomplete_run(self, mock_run_verification: MagicMock) -> None:
+ mock_run_verification.return_value = VerificationResult(wound_down_early=False)
+ before = _incomplete_runs("flags", "deadline")
+
+ verify_and_fix_flags_cache_task()
+
+ assert _incomplete_runs("flags", "deadline") == before
+
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_pushgateway_metrics_recorded_on_success(self, mock_run_verification: MagicMock) -> None:
- mock_run_verification.return_value = MagicMock()
+ mock_run_verification.return_value = VerificationResult()
verify_and_fix_flags_cache_task()
@@ -134,7 +173,7 @@ class TestVerifyAndFixFlagsCacheTaskDisabled(TestCase):
class TestVerifyAndFixTeamMetadataCacheTask(PushGatewayTaskTestMixin, TestCase):
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_verifies_team_metadata_cache(self, mock_run_verification: MagicMock) -> None:
- mock_run_verification.return_value = MagicMock()
+ mock_run_verification.return_value = VerificationResult()
verify_and_fix_team_metadata_cache_task()
@@ -158,7 +197,7 @@ class TestVerifyAndFixTeamMetadataCacheTask(PushGatewayTaskTestMixin, TestCase):
@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()
+ mock_run_verification.return_value = VerificationResult()
# Should not raise
verify_and_fix_team_metadata_cache_task()
@@ -167,7 +206,7 @@ class TestVerifyAndFixTeamMetadataCacheTask(PushGatewayTaskTestMixin, TestCase):
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_pushgateway_metrics_recorded_on_success(self, mock_run_verification: MagicMock) -> None:
- mock_run_verification.return_value = MagicMock()
+ mock_run_verification.return_value = VerificationResult()
verify_and_fix_team_metadata_cache_task()
@@ -198,7 +237,7 @@ class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCas
def test_verifies_flag_definitions_cache(self, mock_run_verification: MagicMock) -> None:
from products.feature_flags.backend.local_evaluation import verify_team_flag_definitions
- mock_run_verification.return_value = MagicMock()
+ mock_run_verification.return_value = VerificationResult()
verify_and_fix_flag_definitions_cache_task()
@@ -246,6 +285,33 @@ class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCas
assert success == 1
assert _incomplete_runs("flag_definitions", reason) == before + 1
+ @patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
+ def test_deadline_winddown_records_incomplete_run_without_raising(self, mock_run_verification: MagicMock) -> None:
+ # flag_definitions runs through its own _run_flag_definitions_verification path,
+ # so its deadline recording is wired separately from the flags/team_metadata path.
+ mock_run_verification.return_value = VerificationResult(wound_down_early=True)
+ before = _incomplete_runs("flag_definitions", "deadline")
+
+ # Should not raise
+ verify_and_fix_flag_definitions_cache_task()
+
+ assert _incomplete_runs("flag_definitions", "deadline") == before + 1
+ success = self.registry.get_sample_value("posthog_celery_verify_and_fix_flag_definitions_cache_task_success")
+ assert success == 1
+
+ @patch("posthog.tasks.hypercache_verification.time.monotonic", return_value=1000.0)
+ @patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
+ def test_passes_monotonic_deadline_to_sweep(
+ self, mock_run_verification: MagicMock, _mock_monotonic: MagicMock
+ ) -> None:
+ # The flag_definitions task threads its own soft time limit down as the deadline.
+ mock_run_verification.return_value = VerificationResult()
+
+ verify_and_fix_flag_definitions_cache_task()
+
+ expected = 1000.0 + (verify_and_fix_flag_definitions_cache_task.soft_time_limit - DEADLINE_HEADROOM_SECONDS)
+ assert mock_run_verification.call_args.kwargs["stop_time"] == expected
+
@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
@@ -261,7 +327,7 @@ class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCas
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_pushgateway_metrics_recorded_on_success(self, mock_run_verification: MagicMock) -> None:
- mock_run_verification.return_value = MagicMock()
+ mock_run_verification.return_value = VerificationResult()
verify_and_fix_flag_definitions_cache_task()