: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(tasks): handle loop retention database errors (#74119)
Alessandro Pogliaghib583ea1e5b9f
diff --git a/products/tasks/backend/loop_retention.py b/products/tasks/backend/loop_retention.pyindex dcfc6041b45a..cdd34919411f 100644--- a/products/tasks/backend/loop_retention.py+++ b/products/tasks/backend/loop_retention.py@@ -7,11 +7,13 @@ non-terminal TaskRun), and prunes old LoopFire dedup rows so that table doesn'tfrom datetime import timedeltafrom uuid import UUID+from django.db import OperationalError, ProgrammingErrorfrom django.db.models import F, Windowfrom django.db.models.functions import RowNumberfrom django.utils import timezone as django_timezoneimport structlog+import psycopg.errorsfrom celery import shared_taskfrom celery.exceptions import SoftTimeLimitExceeded@@ -105,6 +107,14 @@ def sweep_loop_task_retention_task() -> None:deleted_count = sweep_loop_task_retention()except SoftTimeLimitExceeded:raise+ except ProgrammingError as exc:+ if isinstance(exc.__cause__, psycopg.errors.UndefinedTable | psycopg.errors.UndefinedColumn):+ logger.debug("loop_retention.task_sweep_missing_schema", exception=exc)+ else:+ capture_exception(exc)+ logger.exception("loop_retention.task_sweep_failed")+ except OperationalError as exc:+ logger.warning("loop_retention.task_sweep_transient_db_error", exception=exc)except Exception as exc:capture_exception(exc)logger.exception("loop_retention.task_sweep_failed")diff --git a/products/tasks/backend/tests/test_loop_retention.py b/products/tasks/backend/tests/test_loop_retention.pyindex 97c2c41095a3..b75e0dad69d5 100644--- a/products/tasks/backend/tests/test_loop_retention.py+++ b/products/tasks/backend/tests/test_loop_retention.py@@ -2,21 +2,29 @@ from datetime import timedeltafrom unittest.mock import patch-from django.test import TestCase+from django.db import OperationalError, ProgrammingError+from django.test import SimpleTestCase, TestCasefrom django.utils import timezone as django_timezone+import psycopg.errorsfrom parameterized import parameterizedfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from products.tasks.backend.loop_retention import sweep_loop_task_retention+from products.tasks.backend.loop_retention import sweep_loop_task_retention, sweep_loop_task_retention_taskfrom products.tasks.backend.models import Loop, Task, TaskRunRETENTION_MODULE = "products.tasks.backend.loop_retention"+def programming_error_from(cause: BaseException) -> ProgrammingError:+ error = ProgrammingError(str(cause))+ error.__cause__ = cause+ return error++class LoopRetentionTestCase(TestCase):def setUp(self):self.organization = Organization.objects.create(name="Test Org")@@ -53,6 +61,40 @@ class LoopRetentionTestCase(TestCase):return task+class TestSweepLoopTaskRetentionTask(SimpleTestCase):+ @parameterized.expand(+ [+ ("missing_table", programming_error_from(psycopg.errors.UndefinedTable("missing table"))),+ ("missing_column", programming_error_from(psycopg.errors.UndefinedColumn("missing column"))),+ ("transient_database_failure", OperationalError("connection unavailable")),+ ]+ )+ def test_expected_database_errors_are_not_reported(+ self, _name: str, database_error: ProgrammingError | OperationalError+ ) -> None:+ with (+ patch(f"{RETENTION_MODULE}.sweep_loop_task_retention", side_effect=database_error),+ patch(f"{RETENTION_MODULE}.prune_loop_fire_records", return_value=0) as mock_prune,+ patch(f"{RETENTION_MODULE}.capture_exception") as mock_capture,+ ):+ sweep_loop_task_retention_task()++ mock_capture.assert_not_called()+ mock_prune.assert_called_once_with()++ def test_unexpected_programming_errors_are_reported(self) -> None:+ database_error = programming_error_from(psycopg.errors.SyntaxError("invalid query"))+ with (+ patch(f"{RETENTION_MODULE}.sweep_loop_task_retention", side_effect=database_error),+ patch(f"{RETENTION_MODULE}.prune_loop_fire_records", return_value=0) as mock_prune,+ patch(f"{RETENTION_MODULE}.capture_exception") as mock_capture,+ ):+ sweep_loop_task_retention_task()++ mock_capture.assert_called_once_with(database_error)+ mock_prune.assert_called_once_with()++class TestSweepLoopTaskRetention(LoopRetentionTestCase):@parameterized.expand([