: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): retry calculate_cohort_ch on cancelled-query and Postgres transient errors (#77337)
posthog[bot]ef6afef89341
diff --git a/posthog/errors.py b/posthog/errors.pyindex b2bd563a4738..efa9747f42a6 100644--- a/posthog/errors.py+++ b/posthog/errors.py@@ -161,6 +161,11 @@ def wrap_clickhouse_query_error(err: Exception) -> Exception:elif name == "TABLE_IS_READ_ONLY":# Transient: a replica dropped its ZooKeeper/Keeper session and went read-only; it self-heals.return CHQueryErrorTableIsReadOnly(err.message, code=err.code, code_name="table_is_read_only")+ elif name == "QUERY_WAS_CANCELLED":+ # Not retryable by default: a deploy cancelling in-flight queries and a deliberate+ # KILL QUERY are indistinguishable here, so this stays out of CH_TRANSIENT_ERRORS and+ # callers that want the deploy case retried opt in themselves.+ return CHQueryErrorQueryWasCancelled(err.message, code=err.code, code_name="query_was_cancelled")# user query errors - pass through original message with proper code_nameelif name == "ILLEGAL_TYPE_OF_ARGUMENT":@@ -252,6 +257,10 @@ class CHQueryErrorTableIsReadOnly(InternalCHQueryError):pass+class CHQueryErrorQueryWasCancelled(InternalCHQueryError):+ pass++class CHQueryErrorCorruptedParquetMetadata(ExposedCHQueryError):"""A Parquet file backing a warehouse table has corrupted or oversized thrift metadata."""@@ -1033,6 +1042,9 @@ CLICKHOUSE_ERROR_CODE_LOOKUP: dict[int, ErrorCodeMeta] = {# Transient ClickHouse infrastructure errors that are safe to retry.# This can be used in things like celery `autoretry_for` to increase resiliency.# Capacity errors (codes 202/439) are wrapped as ClickHouseAtCapacity by wrap_clickhouse_query_error.+# CHQueryErrorQueryWasCancelled (394) is deliberately absent: a deploy cancelling in-flight queries+# and an operator or user deliberately killing one are indistinguishable at this layer, so callers+# that want the deploy case retried opt in themselves (see COHORT_RECALCULATION_TRANSIENT_ERRORS).CH_TRANSIENT_ERRORS = (CHQueryErrorS3Error,CHQueryErrorS3FileChangedDuringRead,diff --git a/posthog/hogql/test/test_log_query_settings.py b/posthog/hogql/test/test_log_query_settings.pyindex 72ef96c66b1e..d1fd0bda013f 100644--- a/posthog/hogql/test/test_log_query_settings.py+++ b/posthog/hogql/test/test_log_query_settings.py@@ -12,6 +12,7 @@ from posthog.hogql.query import HogQLQueryExecutorfrom posthog.errors import (CH_TRANSIENT_ERRORS,CHQueryErrorCorruptedParquetMetadata,+ CHQueryErrorQueryWasCancelled,CHQueryErrorTableIsReadOnly,CHQueryErrorTooManyBytes,ExposedCHQueryError,@@ -139,6 +140,16 @@ class TestTooManyBytesError(ClickhouseTestMixin, APIBaseTest):assert isinstance(wrapped, CHQueryErrorTableIsReadOnly)assert isinstance(wrapped, CH_TRANSIENT_ERRORS)+ def test_wrap_clickhouse_query_error_query_was_cancelled_is_stable(self):+ # Code 394 (QUERY_WAS_CANCELLED) must map to an importable class so that tasks wanting to+ # retry it (see COHORT_RECALCULATION_TRANSIENT_ERRORS) can name it in an autoretry tuple,+ # rather than falling back to a dynamically generated class nothing can reference. It stays+ # out of CH_TRANSIENT_ERRORS because a deliberate KILL QUERY looks identical here.+ server_error = ServerException("DB::Exception: Query was cancelled.", code=394)+ wrapped = wrap_clickhouse_query_error(server_error)+ assert isinstance(wrapped, CHQueryErrorQueryWasCancelled)+ assert not isinstance(wrapped, CH_TRANSIENT_ERRORS)+class TestCorruptedParquetMetadataError(TestCase):"""A Parquet file with oversized/corrupted thrift metadata surfaces as a raw STD_EXCEPTIONdiff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex 3303ec97a015..3b93eed4d6cf 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -3,12 +3,13 @@ from datetime import datetime, timedeltafrom typing import Optionalfrom django.conf import settings+from django.db import InterfaceError, OperationalErrorfrom django.db.models import Case, DurationField, ExpressionWrapper, F, Q, QuerySet, Whenfrom django.utils import timezoneimport structlogimport posthoganalytics-from celery import Task, chain, current_task, shared_task+from celery import Task, chain, shared_taskfrom dateutil.relativedelta import relativedeltafrom prometheus_client import Counter, Gauge, Histogram@@ -17,7 +18,7 @@ from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.api.monitoring import Featurefrom posthog.clickhouse import query_taggingfrom posthog.clickhouse.query_tagging import QueryTags, update_tags-from posthog.errors import CH_TRANSIENT_ERRORS+from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorQueryWasCancelledfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -41,10 +42,24 @@ from products.cohorts.backend.models.util import (get_all_cohort_dependencies,get_all_cohort_dependents,get_clickhouse_query_stats,+ save_recovery_bookkeeping,sort_cohorts_topologically,)from products.cohorts.backend.realtime_teams import is_cohort_backfill_trigger_team+COHORT_RECALCULATION_MAX_RETRIES = 6++# CH_TRANSIENT_ERRORS plus the Postgres errors calculate_cohort_ch's own ORM reads can hit+# (e.g. a connection-pooler blip before the ClickHouse recalculation even starts). Recalculation is+# a background job nobody cancels by hand, so a cancelled query here means a deploy, not an operator+# shedding load - which is why this task opts into 394 where the shared tuple leaves it out.+COHORT_RECALCULATION_TRANSIENT_ERRORS = (+ *CH_TRANSIENT_ERRORS,+ CHQueryErrorQueryWasCancelled,+ OperationalError,+ InterfaceError,+)+COHORT_RECALCULATIONS_BACKLOG_GAUGE = Gauge("cohort_recalculations_backlog","Number of cohorts that are waiting to be calculated",@@ -459,56 +474,97 @@ def _enqueue_single_cohort_calculation(cohort: Cohort, initiating_user: Optional@shared_task(+ bind=True,ignore_result=True,queue=CeleryQueue.LONG_RUNNING.value,- # Auto-retry for transient ClickHouse errors with exponential backoff- autoretry_for=CH_TRANSIENT_ERRORS,+ # Auto-retry for transient ClickHouse and Postgres errors with exponential backoff+ autoretry_for=COHORT_RECALCULATION_TRANSIENT_ERRORS,retry_backoff=60,retry_backoff_max=1800,- max_retries=6,+ max_retries=COHORT_RECALCULATION_MAX_RETRIES,)@skip_team_scope_audit-def calculate_cohort_ch(cohort_id: int, pending_version: int, initiating_user_id: Optional[int] = None) -> None:+def calculate_cohort_ch(+ self: Task, cohort_id: int, pending_version: int, initiating_user_id: Optional[int] = None+) -> None:with posthoganalytics.new_context():posthoganalytics.tag("feature", Feature.COHORT.value)posthoganalytics.tag("cohort_id", cohort_id)- cohort: Cohort = Cohort.objects.get(pk=cohort_id)-- # Skip calculation if this version is now obsolete (superseded by newer save)- if cohort.pending_version and pending_version < cohort.pending_version:- logger.info(- "cohort_calculation_skipped_obsolete",- cohort_id=cohort_id,- task_version=pending_version,- current_pending_version=cohort.pending_version,- )- return-- posthoganalytics.tag("team_id", cohort.team.id)+ try:+ cohort: Cohort = Cohort.objects.get(pk=cohort_id)- staleness_hours = 0.0- if cohort.last_calculation is not None:- staleness_hours = (timezone.now() - cohort.last_calculation).total_seconds() / 3600- COHORT_STALENESS_HOURS_GAUGE.set(staleness_hours)+ # Skip calculation if this version is now obsolete (superseded by newer save)+ if cohort.pending_version and pending_version < cohort.pending_version:+ logger.info(+ "cohort_calculation_skipped_obsolete",+ cohort_id=cohort_id,+ task_version=pending_version,+ current_pending_version=cohort.pending_version,+ )+ return- tags = QueryTags(cohort_id=cohort_id, feature=query_tagging.Feature.COHORT)- if initiating_user_id:- tags.user_id = initiating_user_id- if current_task and current_task.request and current_task.request.id:- tags.celery_task_id = current_task.request.id- update_tags(tags)+ posthoganalytics.tag("team_id", cohort.team_id)++ staleness_hours = 0.0+ if cohort.last_calculation is not None:+ staleness_hours = (timezone.now() - cohort.last_calculation).total_seconds() / 3600+ COHORT_STALENESS_HOURS_GAUGE.set(staleness_hours)++ tags = QueryTags(cohort_id=cohort_id, feature=query_tagging.Feature.COHORT)+ if initiating_user_id:+ tags.user_id = initiating_user_id+ if self.request.id:+ tags.celery_task_id = self.request.id+ update_tags(tags)+ except Exception as err:+ # Recalculation never started - calculate_people_ch's own bookkeeping (which handles+ # is_calculating/errors_calculating for failures during recalculation) never ran either.+ # When nothing will retry, clear is_calculating here rather than leaving the cohort+ # stranded "in flight" until the hourly reset_stuck_cohorts job, which would then charge+ # it an errors_calculating increment for a recalculation that never actually ran.+ if _is_final_attempt(self, err, COHORT_RECALCULATION_TRANSIENT_ERRORS):+ # pending_version guard extends _safe_reset_calculating_state with a null leg: never+ # clear the flag out from under a newer calculation that superseded this one. A null+ # pending_version means nothing newer is queued, so it clears too.+ #+ # errors_calculating and last_error_at are stamped alongside because they are the+ # only brakes on re-enqueueing: last_error_at drives the exponential backoff and+ # errors_calculating drives the MAX_ERRORS_CALCULATING cutoff. Clearing+ # is_calculating without them would make a cohort failing here eligible again every+ # cycle, forever. A later successful run resets both in calculate_people_ch.+ save_recovery_bookkeeping(+ lambda: Cohort.objects.filter(+ Q(pending_version__lte=pending_version) | Q(pending_version__isnull=True),+ pk=cohort_id,+ is_calculating=True,+ ).update(+ is_calculating=False,+ errors_calculating=F("errors_calculating") + 1,+ last_error_at=timezone.now(),+ ),+ cohort_id=cohort_id,+ )+ raise- cohort.calculate_people_ch(pending_version, initiating_user_id=initiating_user_id)+ cohort.calculate_people_ch(+ pending_version,+ initiating_user_id=initiating_user_id,+ # calculate_people_ch charges errors_calculating in its own except block and cannot see+ # the retry machinery above it. Without this it would charge one increment per attempt,+ # so a single fully-failed run would push a cohort most of the way to the+ # MAX_ERRORS_CALCULATING cutoff that permanently drops it from recalculation.+ will_retry=lambda err: not _is_final_attempt(self, err, COHORT_RECALCULATION_TRANSIENT_ERRORS),+ )-def _is_final_attempt(task: Task, err: Exception) -> bool:+def _is_final_attempt(task: Task, err: Exception, retryable_errors: tuple[type[BaseException], ...]) -> bool:"""Whether a failure is permanent, so the task must finalize terminal state now.- Nothing retries an error outside CH_TRANSIENT_ERRORS, a direct (synchronous) call, which has no- Celery retry machinery behind it, or the last autoretry attempt.+ Nothing retries an error outside the task's retryable set, a direct (synchronous) call, which+ has no Celery retry machinery behind it, or the last autoretry attempt."""- if not isinstance(err, CH_TRANSIENT_ERRORS):+ if not isinstance(err, retryable_errors):return Trueif task.request.called_directly:return True@@ -585,7 +641,7 @@ def calculate_cohort_from_list(# raise_on_error also hands terminal-state finalization to us, so record the failure, but# only when nothing will retry. Recording it while attempts remain would leave a cohort# that is still being retried looking errored and no longer calculating.- if _is_final_attempt(self, err):+ if _is_final_attempt(self, err, CH_TRANSIENT_ERRORS):cohort._safe_save_cohort_state(team_id=team_id, processing_error=err)raiselogger.warn(diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.pyindex 0a1198a47295..68dc535af2d4 100644--- a/posthog/tasks/test/test_calculate_cohort.py+++ b/posthog/tasks/test/test_calculate_cohort.py@@ -1,9 +1,11 @@from collections.abc import Callable+from typing import Optionalfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.db import InterfaceError, OperationalErrorfrom django.test import override_settingsfrom django.utils import timezone@@ -13,16 +15,19 @@ from parameterized import parameterizedfrom posthog.hogql.errors import QueryError+from posthog.errors import CHQueryErrorQueryWasCancelledfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.tasks.calculate_cohort import (COHORT_BACKFILL_REFUSAL_OUTCOMES,COHORT_BACKFILL_TRIGGER_TASK_COUNTER,+ COHORT_RECALCULATION_MAX_RETRIES,COHORT_STUCK_COUNT_GAUGE,COHORTS_STALE_COUNT_GAUGE,COHORTS_TOTAL_GAUGE,MAX_AGE_MINUTES,MAX_ERRORS_CALCULATING,MAX_STUCK_COHORTS_TO_RESET,+ calculate_cohort_ch,calculate_cohort_from_list,enqueue_cohorts_to_calculate,increment_version_and_enqueue_calculate_cohort,@@ -1292,6 +1297,123 @@ class TestCohortCalculationTasks(APIBaseTest):mock_flags_cache.delay.assert_not_called()mock_hog_refresh.delay.assert_not_called()+ def _run_calculate_cohort_ch(+ self, cohort_id: int, pending_version: int = 1, *, retries: int = 0, called_directly: bool = False+ ) -> None:+ task = calculate_cohort_ch+ task.push_request(retries=retries, called_directly=called_directly, is_eager=True)+ try:+ task.run(cohort_id, pending_version)+ finally:+ task.pop_request()++ @parameterized.expand(+ [+ ("operational_error", OperationalError("connection reset")),+ ("interface_error", InterfaceError("connection already closed")),+ ]+ )+ def test_calculate_cohort_ch_schedules_a_retry_and_keeps_is_calculating(self, _name: str, error: Exception) -> None:+ # A connection-pooler blip on the task's first ORM read used to strand the cohort "in+ # flight" for an hour, until reset_stuck_cohorts caught it.+ # Celery raising Retry rather than the original error is what proves one was scheduled, and+ # is_calculating must not be cleared while the recalculation still has attempts left.+ cohort = Cohort.objects.create(team=self.team, name="test_cohort", is_calculating=True, pending_version=1)++ with (+ patch.object(Cohort.objects, "get", side_effect=error),+ self.assertRaises(Retry),+ ):+ self._run_calculate_cohort_ch(cohort.id)++ cohort.refresh_from_db()+ self.assertTrue(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 0)++ @parameterized.expand(+ [+ # pending_version 1 is the shape every real cohort reaches this task with:+ # _prepare_cohort_for_calculation stamps it in the same save that sets is_calculating.+ ("non_retryable_error", ValueError("boom"), 0, False, 1),+ ("retries_exhausted", OperationalError("connection reset"), COHORT_RECALCULATION_MAX_RETRIES, False, 1),+ ("called_directly", OperationalError("connection reset"), 0, True, 1),+ # Documented fallback: a cohort that never got a pending_version still has to clear.+ ("null_pending_version", ValueError("boom"), 0, False, None),+ ]+ )+ def test_calculate_cohort_ch_clears_is_calculating_when_recalculation_will_not_be_retried(+ self, _name: str, error: Exception, retries: int, called_directly: bool, pending_version: Optional[int]+ ) -> None:+ # Whether the error can never be retried, retries are exhausted, or the task was called+ # synchronously (the management command) so no retry machinery is behind it, the+ # recalculation is never going to run again - the cohort must not stay "in flight" until+ # the hourly reset_stuck_cohorts job. errors_calculating and last_error_at have to be+ # stamped with it, because they are the only brakes on re-enqueueing the cohort against a+ # database that is still failing.+ cohort = Cohort.objects.create(+ team=self.team, name="test_cohort", is_calculating=True, pending_version=pending_version+ )++ with patch.object(Cohort.objects, "get", side_effect=error):+ with self.assertRaises(type(error)):+ self._run_calculate_cohort_ch(cohort.id, retries=retries, called_directly=called_directly)++ cohort.refresh_from_db()+ self.assertFalse(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 1)+ self.assertIsNotNone(cohort.last_error_at)++ def test_calculate_cohort_ch_retries_when_a_deploy_cancels_the_recalculation_query(self) -> None:+ # The reason 394 got an importable class: a deploy cancelling the in-flight recalculation+ # query has to be retried rather than killing the task outright, and a pending retry has to+ # leave the cohort looking exactly like a running one. errors_calculating must stay at 0 -+ # charged per attempt instead of per failed run, a single bad deploy would push the cohort+ # most of the way to the MAX_ERRORS_CALCULATING cutoff that drops it from recalculation for+ # good. is_calculating must stay set, because with the counter deliberately unstamped it is+ # the only thing keeping the cohort out of the scheduler's candidate queryset during the+ # backoff - a superseding calculation would bump pending_version and no-op the retry.+ cohort = Cohort.objects.create(team=self.team, name="test_cohort", is_calculating=True, pending_version=1)++ with (+ patch(+ "products.cohorts.backend.models.util.recalculate_cohortpeople",+ side_effect=CHQueryErrorQueryWasCancelled(+ "Query was cancelled.", code=394, code_name="query_was_cancelled"+ ),+ ),+ self.assertRaises(Retry),+ ):+ self._run_calculate_cohort_ch(cohort.id)++ cohort.refresh_from_db()+ self.assertTrue(cohort.is_calculating)+ self.assertEqual(cohort.errors_calculating, 0)+ self.assertIsNone(cohort.last_error_at)++ def test_calculate_cohort_ch_skips_an_obsolete_pending_version(self) -> None:+ # A newer save superseded this task's version. Without the guard both tasks would run a+ # full ClickHouse recalculation of the same cohort side by side.+ cohort = Cohort.objects.create(team=self.team, name="test_cohort", is_calculating=True)+ Cohort.objects.filter(pk=cohort.pk).update(pending_version=4)++ with patch.object(Cohort, "calculate_people_ch") as mock_calculate:+ self._run_calculate_cohort_ch(cohort.id, 2)++ mock_calculate.assert_not_called()++ def test_calculate_cohort_ch_leaves_is_calculating_for_a_newer_pending_version(self) -> None:+ # A newer save bumped pending_version and enqueued its own task. This older task failing+ # must not clear the flag out from under the calculation that superseded it.+ cohort = Cohort.objects.create(team=self.team, name="test_cohort", is_calculating=True)+ Cohort.objects.filter(pk=cohort.pk).update(pending_version=4)++ with patch.object(Cohort.objects, "get", side_effect=ValueError("boom")):+ with self.assertRaises(ValueError):+ self._run_calculate_cohort_ch(cohort.id, 2)++ cohort.refresh_from_db()+ self.assertTrue(cohort.is_calculating)+def test_insert_cohort_from_query_count_updated_on_exception(self) -> None:from posthog.tasks.calculate_cohort import insert_cohort_from_querydiff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex b04b548197b6..9b6dec8fc359 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -655,7 +655,23 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):is_calculating=False)- def calculate_people_ch(self, pending_version: int, *, initiating_user_id: Optional[int] = None):+ def calculate_people_ch(+ self,+ pending_version: int,+ *,+ initiating_user_id: Optional[int] = None,+ will_retry: Optional[Callable[[Exception], bool]] = None,+ ):+ """+ Args:+ will_retry: Told the exception that just failed the recalculation, answers whether the+ caller will run it again. A pending retry leaves the cohort exactly as a still-running+ one looks: `is_calculating` set, `errors_calculating` and `last_error_at` untouched.+ Those fields gate the re-enqueue backoff and the `MAX_ERRORS_CALCULATING` cutoff, so+ the counter is charged once per failed episode rather than once per attempt, and the+ flag keeps the scheduler off the cohort meanwhile. Callers that auto-retry pass this;+ a caller that omits it is treated as one attempt per failure.+ """from products.cohorts.backend.models.util import recalculate_cohortpeople, save_recovery_bookkeepinglogger.info(@@ -672,6 +688,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):# 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 0+ retry_pending = Falsetry:count = recalculate_cohortpeople(self, pending_version, initiating_user_id=initiating_user_id)self.count = count@@ -693,9 +710,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):self.last_calculation = timezone.now()self.errors_calculating = 0self.last_error_at = None- except Exception:- self.errors_calculating = starting_errors_calculating + 1- self.last_error_at = timezone.now()+ except Exception as err:+ retry_pending = bool(will_retry and will_retry(err))+ if not retry_pending:+ self.errors_calculating = starting_errors_calculating + 1+ self.last_error_at = timezone.now()logger.warning("cohort_calculation_failed",@@ -725,11 +744,20 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):# 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,- )+ #+ # A pending retry keeps the flag set, because it is the only thing holding the cohort out+ # of the scheduler's candidate queryset during the backoff window. Clearing it here while+ # the error counter is deliberately unstamped would let the scheduler enqueue a+ # superseding calculation within a minute, which bumps pending_version and no-ops the+ # retry - so a failing cohort would re-enter the queue every tick, never advance+ # errors_calculating, and never reach the MAX_ERRORS_CALCULATING cutoff. If the retry+ # never lands (worker death), reset_stuck_cohorts still recovers the flag.+ if not retry_pending:+ save_recovery_bookkeeping(+ lambda: self._safe_reset_calculating_state(completed_version=pending_version),+ cohort_id=self.pk,+ team_id=self.team_id,+ )self.refresh_from_db()diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex 03523e02ca48..ba751136c7c3 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -152,7 +152,7 @@ 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:+def save_recovery_bookkeeping(save_fn: Callable[[], None], *, cohort_id: int, team_id: int | None = None) -> 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