: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(cohorts): survive dropped connection during recalculation recovery (#69735)
posthog[bot]ef3d402aaf7d
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex a88e73d892c4..0f48eae93dfe 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -567,7 +567,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):)def calculate_people_ch(self, pending_version: int, *, initiating_user_id: Optional[int] = None):- from products.cohorts.backend.models.util import recalculate_cohortpeople+ from products.cohorts.backend.models.util import recalculate_cohortpeople, save_recovery_bookkeepinglogger.info("cohort_calculation_started",@@ -578,6 +578,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):start_time = time.monotonic()cohort_type_cleared = False+ # Snapshot the current error count while the connection is healthy so the error-path+ # increment below is a concrete int, not an F() expression. save_recovery_bookkeeping+ # may replay the finally-save, and a replayed F("errors_calculating") + 1 would count a+ # single failure twice if the first write committed before the connection dropped.+ starting_errors_calculating = self.errors_calculating or 0try:count = recalculate_cohortpeople(self, pending_version, initiating_user_id=initiating_user_id)self.count = count@@ -600,7 +605,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):self.errors_calculating = 0self.last_error_at = Noneexcept Exception:- self.errors_calculating = F("errors_calculating") + 1+ self.errors_calculating = starting_errors_calculating + 1self.last_error_at = timezone.now()logger.warning(@@ -613,13 +618,29 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):raisefinally:- # Save fields modified during calculation, but exclude is_calculating to prevent race condition- self.save(- update_fields=["last_calculation", "errors_calculating", "last_error_at", "cohort_type", "groups"]+ # Save fields modified during calculation, but exclude is_calculating to prevent race+ # condition. `groups` is included because accessing self.properties during calculation+ # normalizes deprecated inline group properties in place, and that normalization must be+ # persisted. Persist resiliently: a Postgres connection dropped mid-recalculation would+ # otherwise make this save fail with "connection is closed", masking the real error and+ # leaving the cohort stuck calculating (the reconnect also lets the is_calculating reset+ # below succeed).+ save_recovery_bookkeeping(+ lambda: self.save(+ update_fields=["last_calculation", "errors_calculating", "last_error_at", "cohort_type", "groups"]+ ),+ cohort_id=self.pk,+ team_id=self.team_id,+ )+ # Only set is_calculating = False if this is the highest pending version. This prevents the+ # flag from being reset while other higher-version calculations are still running. Route it+ # through the same reconnect-and-retry: it is a bookkeeping write on the same connection, so+ # an unguarded failure here would mask the real error and leave is_calculating stuck True.+ save_recovery_bookkeeping(+ lambda: self._safe_reset_calculating_state(completed_version=pending_version),+ cohort_id=self.pk,+ team_id=self.team_id,)- # Only set is_calculating = False if this is the highest pending version- # This prevents the flag from being reset while other higher-version calculations are still running- self._safe_reset_calculating_state(completed_version=pending_version)self.refresh_from_db()diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.pyindex 0aea83008fd0..17242f001b80 100644--- a/products/cohorts/backend/models/test/test_util.py+++ b/products/cohorts/backend/models/test/test_util.py@@ -1,6 +1,8 @@from posthog.test.base import BaseTest, _create_person, flush_persons_and_eventsfrom unittest.mock import MagicMock, patch+from django.db import DEFAULT_DB_ALIAS, OperationalError+from clickhouse_driver.errors import SocketTimeoutErrorfrom parameterized import parameterizedfrom pydantic import (@@ -24,6 +26,7 @@ from posthog.models.person.sql import PERSON_STATIC_COHORT_TABLEfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.cohorts.backend.models.util import (CohortErrorCode,+ _recalculate_cohortpeople_for_team,_sanitize_query_for_cohort,get_all_cohort_dependencies,get_friendly_error_message,@@ -1108,3 +1111,70 @@ class TestGetFriendlyErrorMessage(BaseTest):message = get_friendly_error_message("some_unknown_code")assert message is not Noneself.assertIn("an error occurred", message.lower())+++class TestRecalculationErrorRecovery(BaseTest):+ def test_original_error_surfaces_when_recovery_history_save_fails(self):+ # When Postgres drops the connection mid-recalculation, the error-recovery history.save+ # fails too. The recovery path must reconnect, retry the bookkeeping, and still let the real+ # calculation error propagate instead of a cascading "connection is closed" masking it.+ cohort = _create_cohort(+ team=self.team,+ name="c",+ groups=[{"properties": [{"key": "name", "value": "test", "type": "person"}]}],+ )+ real_error = RuntimeError("real root cause")+ mock_history = MagicMock()+ # Both the initial save and the post-reconnect retry fail, exercising the swallow path.+ mock_history.save.side_effect = OperationalError("the connection is closed")++ with (+ patch(+ "products.cohorts.backend.models.util.CohortCalculationHistory.objects.create",+ return_value=mock_history,+ ),+ patch(+ "products.cohorts.backend.models.util._recalculate_cohortpeople_for_team_hogql",+ side_effect=real_error,+ ),+ # Patch connections so the reconnect doesn't close the real test transaction's connection.+ patch("products.cohorts.backend.models.util.connections") as mock_connections,+ ):+ with self.assertRaises(RuntimeError) as ctx:+ _recalculate_cohortpeople_for_team(cohort, 0, self.team)++ self.assertIs(ctx.exception, real_error)+ assert mock_history.save.call_count == 2+ mock_connections[DEFAULT_DB_ALIAS].close.assert_called_once()++ def test_original_error_surfaces_when_reset_calculating_save_fails(self):+ # calculate_people_ch's finally block resets is_calculating on the same connection the recovery+ # bookkeeping save uses. If that reset write hits the dropped connection it must not raise out of+ # finally and mask the real calculation error - it runs through the same reconnect-and-retry.+ cohort = _create_cohort(+ team=self.team,+ name="c",+ groups=[{"properties": [{"key": "name", "value": "test", "type": "person"}]}],+ )+ real_error = RuntimeError("real root cause")++ with (+ patch(+ "products.cohorts.backend.models.util.recalculate_cohortpeople",+ side_effect=real_error,+ ),+ # The is_calculating reset write fails on the dropped connection, initial attempt and retry.+ patch.object(+ Cohort,+ "_safe_reset_calculating_state",+ side_effect=OperationalError("the connection is closed"),+ ) as mock_reset,+ # Patch connections so the reconnect doesn't close the real test transaction's connection.+ patch("products.cohorts.backend.models.util.connections") as mock_connections,+ ):+ with self.assertRaises(RuntimeError) as ctx:+ cohort.calculate_people_ch(pending_version=0)++ self.assertIs(ctx.exception, real_error)+ assert mock_reset.call_count == 2+ mock_connections[DEFAULT_DB_ALIAS].close.assert_called_once()diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex 7b79b117e67d..425c9d1dc357 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -2,12 +2,13 @@ from __future__ import annotationsimport copyimport uuid-from collections.abc import Sequence+from collections.abc import Callable, Sequencefrom datetime import datetime, timedeltafrom enum import StrEnumfrom typing import TYPE_CHECKING, Any, Optional, Union, castfrom django.conf import settings+from django.db import DEFAULT_DB_ALIAS, InterfaceError, OperationalError, connectionsfrom django.utils import timezoneimport structlog@@ -35,6 +36,7 @@ from posthog.exceptions import (ClickHouseQuerySizeExceeded,ClickHouseQueryTimeOut,)+from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Filter, Teamfrom posthog.models.person.sql import (DELETE_PERSON_FROM_STATIC_COHORT,@@ -149,6 +151,30 @@ COHORT_STATS_COLLECTION_DELAY_SECONDS = 60 # Short delay to allow query_log tologger = structlog.get_logger(__name__)+def save_recovery_bookkeeping(save_fn: Callable[[], None], *, cohort_id: int, team_id: int) -> None:+ """Persist post-calculation bookkeeping, surviving a Postgres connection dropped mid-recalculation.++ A long recalculation can outlive its connection (the server closes it unexpectedly); the first+ write afterwards then raises a connection error. Left unguarded on the error/finally recovery+ path, that cascades into "the connection is closed" - burying the real root-cause error and+ leaving the cohort stuck with is_calculating=True. Reconnect and retry once so the bookkeeping+ still lands and the original error is what propagates; if the retry fails too, swallow it (a+ recovery write must never mask the failure it is recording).+ """+ try:+ save_fn()+ except (InterfaceError, OperationalError):+ connections[DEFAULT_DB_ALIAS].close() # next query opens a fresh connection+ try:+ save_fn()+ except Exception as retry_error:+ # A swallowed retry means the cohort is stuck with is_calculating=True and no bookkeeping+ # recorded. Surface it to error tracking, matching how other swallowed cohort-calculation+ # errors are captured, so it alerts rather than only living in structured logs.+ logger.warning("cohort_recalc_recovery_save_failed", cohort_id=cohort_id, team_id=team_id, exc_info=True)+ capture_exception(retry_error, additional_properties={"cohort_id": cohort_id, "team_id": team_id})++def run_cohort_query(fn, *args, cohort_id: int, history: CohortCalculationHistory | None = None, query: str | None = None, **kwargs):@@ -739,7 +765,14 @@ def _recalculate_cohortpeople_for_team(cohort: Cohort, pending_version: int, teahistory.finished_at = timezone.now()history.error = str(e)history.error_code = parse_error_code(e)- history.save(update_fields=["finished_at", "error", "error_code"])+ # The recalculation may have died because Postgres dropped the connection; record the+ # failure resiliently so it reconnects instead of re-raising "connection is closed" and+ # masking the real error e.+ save_recovery_bookkeeping(+ lambda: history.save(update_fields=["finished_at", "error", "error_code"]),+ cohort_id=cohort.pk,+ team_id=team.id,+ )raise