: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(web-analytics): release the achievement debounce key when task publish fails (#99890)
Jordan Mryyandbf8f6ce3aa9
diff --git a/products/web_analytics/backend/achievements/tasks.py b/products/web_analytics/backend/achievements/tasks.pyindex df90732c85f3..d6be755c3984 100644--- a/products/web_analytics/backend/achievements/tasks.py+++ b/products/web_analytics/backend/achievements/tasks.py@@ -14,6 +14,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.scoping_audit import skip_team_scope_audit+from posthog.utils import safe_cache_deletefrom products.notifications.backend.facade.api import (NotificationData,@@ -90,15 +91,21 @@ def enqueue_recompute_web_analytics_achievements_debounced(team_id: int, user_idscope = str(user_id) if user_id is not None else "team"debounce_key = f"wa_achievements_recompute:{team_id}:{scope}:{today.isoformat()}"try:- was_added = cache.add(debounce_key, "1", timeout=RECOMPUTE_DEBOUNCE_TTL_SECONDS)+ claimed = cache.add(debounce_key, "1", timeout=RECOMPUTE_DEBOUNCE_TTL_SECONDS)except Exception as e:logger.warning("wa_achievements_debounce_cache_failure", team_id=team_id, exc_info=True)capture_exception(e)- was_added = True- if was_added:+ claimed = False+ else:+ if not claimed:+ return False+ try:recompute_web_analytics_achievements.delay(team_id, user_id=user_id)- return True- return False+ except Exception:+ if claimed:+ safe_cache_delete(debounce_key)+ raise+ return Truedef recompute_web_analytics_achievements_sync(diff --git a/products/web_analytics/backend/test/test_achievements_tasks.py b/products/web_analytics/backend/test/test_achievements_tasks.pyindex 047389483085..3e3565a1a581 100644--- a/products/web_analytics/backend/test/test_achievements_tasks.py+++ b/products/web_analytics/backend/test/test_achievements_tasks.py@@ -1,9 +1,12 @@-from collections.abc import Callable-from datetime import timedelta+from collections.abc import Callable, Iterator+from contextlib import contextmanager+from datetime import date, timedeltafrom posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patch+from django.core.cache import cache+from django.test import SimpleTestCasefrom django.utils import timezonefrom products.web_analytics.backend.achievements import tasks@@ -157,3 +160,49 @@ class TestRecomputeTask(BaseTest):):tasks.recompute_web_analytics_achievements(self.team.id, self.user.id)self.assertFalse(WebAnalyticsAchievementProgress.objects.for_team(self.team.id).filter(user=self.user).exists())+++class TestAchievementEnqueueRecovery(SimpleTestCase):+ today = date(2026, 1, 2)++ def setUp(self) -> None:+ super().setUp()+ cache.clear()++ @contextmanager+ def _publish_fails(self) -> Iterator[MagicMock]:+ with patch.object(+ tasks.recompute_web_analytics_achievements, "delay", side_effect=RuntimeError("Publish failed")+ ) as publish:+ yield publish++ def test_publish_failure_allows_retry_and_success_retains_daily_debounce(self) -> None:+ with patch.object(tasks.recompute_web_analytics_achievements, "delay") as publish:+ publish.side_effect = RuntimeError("Publish failed")+ with self.assertRaisesMessage(RuntimeError, "Publish failed"):+ tasks.enqueue_recompute_web_analytics_achievements_debounced(12, None, self.today)+ publish.side_effect = None+ self.assertTrue(tasks.enqueue_recompute_web_analytics_achievements_debounced(12, None, self.today))+ self.assertFalse(tasks.enqueue_recompute_web_analytics_achievements_debounced(12, None, self.today))+ self.assertEqual(publish.call_count, 2)+ publish.assert_called_with(12, user_id=None)++ def test_cleanup_failure_does_not_hide_the_original_publish_error(self) -> None:+ with (+ self._publish_fails(),+ patch.object(tasks.cache, "delete", side_effect=RuntimeError("Cache unavailable")) as delete,+ ):+ with self.assertRaisesMessage(RuntimeError, "Publish failed"):+ tasks.enqueue_recompute_web_analytics_achievements_debounced(12, None, self.today)+ delete.assert_called_once()++ def test_cache_fail_open_does_not_delete_an_unclaimed_key_after_publish_failure(self) -> None:+ with (+ self._publish_fails(),+ patch.object(tasks.cache, "add", side_effect=RuntimeError("Cache unavailable")),+ patch.object(tasks.cache, "delete") as delete,+ patch.object(tasks, "capture_exception"),+ ):+ with self.assertRaisesMessage(RuntimeError, "Publish failed"):+ tasks.enqueue_recompute_web_analytics_achievements_debounced(12, None, self.today)+ delete.assert_not_called()