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(cohorts): retry transient personhog population errors (#96278)

Matheus Batistae0a98b890d45
diff --git a/posthog/personhog_client/interceptor.py b/posthog/personhog_client/interceptor.py
index d4ad878db792..48a8fad467fe 100644
--- a/posthog/personhog_client/interceptor.py
+++ b/posthog/personhog_client/interceptor.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import time
import random
from collections import namedtuple
-from collections.abc import Sequence
+from collections.abc import Collection, Sequence
from typing import Any
import grpc
@@ -159,6 +159,22 @@ _RETRYABLE_CODES = frozenset(
)
+def is_transient_rpc_error(exc: BaseException, codes: Collection[grpc.StatusCode] = _RETRYABLE_CODES) -> bool:
+ """Whether ``exc``, or the error it was raised from, is a gRPC failure with a status in ``codes``.
+
+ Follows ``__cause__`` so a caller that wrapped the RpcError (``personhog_call(reraise_as=...)``)
+ still classifies the underlying transport failure. ``codes`` defaults to the in-process
+ RetryInterceptor policy; a caller that retries at a slower tier passes its own set.
+ """
+ current: BaseException | None = exc
+ while current is not None:
+ if isinstance(current, grpc.RpcError):
+ code = getattr(current, "code", None)
+ return callable(code) and code() in codes
+ current = current.__cause__
+ return False
+
+
class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):
"""Retries transient gRPC errors with jittered backoff.
diff --git a/posthog/personhog_client/test_retry_interceptor.py b/posthog/personhog_client/test_retry_interceptor.py
index b843dc38799d..5f96a4dcd44b 100644
--- a/posthog/personhog_client/test_retry_interceptor.py
+++ b/posthog/personhog_client/test_retry_interceptor.py
@@ -3,10 +3,17 @@ from __future__ import annotations
import pytest
from unittest.mock import MagicMock, patch
+from django.db import DatabaseError
+
import grpc
from parameterized import parameterized
-from posthog.personhog_client.interceptor import RetryInterceptor, _MutableClientCallDetails
+from posthog.personhog_client.interceptor import (
+ _RETRYABLE_CODES,
+ RetryInterceptor,
+ _MutableClientCallDetails,
+ is_transient_rpc_error,
+)
def _make_call_details(
@@ -180,3 +187,39 @@ class TestRetryInterceptorMetrics:
mock_retries.labels.return_value.inc.assert_not_called()
mock_terminal.labels.return_value.inc.assert_not_called()
+
+
+def _wrapped_in_database_error(cause: BaseException) -> BaseException:
+ wrapped = DatabaseError("personhog insert_cohort_members failed")
+ wrapped.__cause__ = cause
+ return wrapped
+
+
+class TestIsTransientRpcError:
+ @parameterized.expand(
+ [
+ ("retryable_code", _make_rpc_error(grpc.StatusCode.UNAVAILABLE), _RETRYABLE_CODES, True),
+ ("terminal_code", _make_rpc_error(grpc.StatusCode.INVALID_ARGUMENT), _RETRYABLE_CODES, False),
+ ("not_an_rpc_error", ValueError("boom"), _RETRYABLE_CODES, False),
+ (
+ "wrapped_retryable_cause",
+ _wrapped_in_database_error(_make_rpc_error(grpc.StatusCode.UNAVAILABLE)),
+ _RETRYABLE_CODES,
+ True,
+ ),
+ (
+ "code_outside_the_given_set",
+ _make_rpc_error(grpc.StatusCode.RESOURCE_EXHAUSTED),
+ _RETRYABLE_CODES,
+ False,
+ ),
+ (
+ "caller_supplied_codes",
+ _make_rpc_error(grpc.StatusCode.RESOURCE_EXHAUSTED),
+ {grpc.StatusCode.RESOURCE_EXHAUSTED},
+ True,
+ ),
+ ]
+ )
+ def test_classifies_transport_failures(self, _name: str, exc: BaseException, codes, expected: bool):
+ assert is_transient_rpc_error(exc, codes=codes) is expected
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index 4123813d3207..66f48de7898c 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -1,15 +1,19 @@
import time
+from collections.abc import Callable
from datetime import datetime, timedelta
-from typing import Optional
+from typing import Any, Optional
from django.conf import settings
from django.db import InterfaceError, OperationalError
from django.db.models import Case, DurationField, ExpressionWrapper, F, Q, QuerySet, When
from django.utils import timezone
+import grpc
import structlog
import posthoganalytics
from celery import Task, chain, shared_task
+from celery.exceptions import Retry, SoftTimeLimitExceeded
+from celery.utils.time import get_exponential_backoff_interval
from dateutil.relativedelta import relativedelta
from prometheus_client import Counter, Gauge, Histogram
@@ -22,6 +26,7 @@ from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorQueryWasCancelled
from posthog.exceptions_capture import capture_exception
from posthog.models.team.team import Team
from posthog.models.user import User
+from posthog.personhog_client.interceptor import is_transient_rpc_error
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
@@ -48,11 +53,33 @@ from products.cohorts.backend.models.util import (
from products.cohorts.backend.realtime_teams import is_cohort_backfill_trigger_team
COHORT_RECALCULATION_MAX_RETRIES = 6
+STATIC_POPULATION_MAX_RETRIES = 6
+STATIC_POPULATION_RETRY_BACKOFF_SECONDS = 60
+STATIC_POPULATION_RETRY_BACKOFF_MAX_SECONDS = 1800
+STATIC_POPULATION_SOFT_TIME_LIMIT_SECONDS = 4 * 60 * 60
+
+# The RetryInterceptor set plus RESOURCE_EXHAUSTED and INTERNAL, which an in-process retry must not
+# hammer but a task backoff of minutes is the right answer to. Personhog sheds load with
+# RESOURCE_EXHAUSTED and maps every Postgres query error (deadlock, lock or statement timeout, a
+# read-only primary after a failover) to INTERNAL. UNKNOWN stays in because an HTTP/2 stream reset
+# ("Stream removed") surfaces as UNKNOWN, and that is the outage shape that leaves a static cohort
+# half-synced.
+STATIC_POPULATION_RETRYABLE_RPC_CODES = frozenset(
+ {
+ grpc.StatusCode.UNAVAILABLE,
+ grpc.StatusCode.DEADLINE_EXCEEDED,
+ grpc.StatusCode.ABORTED,
+ grpc.StatusCode.UNKNOWN,
+ grpc.StatusCode.RESOURCE_EXHAUSTED,
+ grpc.StatusCode.INTERNAL,
+ }
+)
-# 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.
+# CH_TRANSIENT_ERRORS plus the Postgres errors the cohort tasks' own ORM statements can hit (e.g. a
+# connection-pooler blip before the ClickHouse work even starts, or between two personhog batches).
+# Recalculation and static population are background jobs nobody cancels by hand, so a cancelled
+# query here means a deploy, not an operator shedding load - which is why they opt into 394 where
+# the shared tuple leaves it out.
COHORT_RECALCULATION_TRANSIENT_ERRORS = (
*CH_TRANSIENT_ERRORS,
CHQueryErrorQueryWasCancelled,
@@ -60,6 +87,11 @@ COHORT_RECALCULATION_TRANSIENT_ERRORS = (
InterfaceError,
)
+# The recalculation set plus the soft time limit, which static population opts into because it can
+# resume: the ClickHouse insert excludes the actors it already wrote and personhog ignores existing
+# membership. Recording the limit as terminal would strand a half-written cohort instead.
+STATIC_POPULATION_TRANSIENT_ERRORS = (*COHORT_RECALCULATION_TRANSIENT_ERRORS, SoftTimeLimitExceeded)
+
COHORT_RECALCULATIONS_BACKLOG_GAUGE = Gauge(
"cohort_recalculations_backlog",
"Number of cohorts that are waiting to be calculated",
@@ -129,6 +161,12 @@ COHORT_CALCULATION_DURATION_SECONDS = Histogram(
buckets=[1, 5, 10, 30, 60, 120, 300, 600, 1800, 3600],
)
+COHORT_STATIC_POPULATION_RETRIES_COUNTER = Counter(
+ "cohort_static_population_retries_total",
+ "Static cohort population attempts that failed transiently and scheduled a task retry",
+ ["task", "error_type"],
+)
+
logger = structlog.get_logger(__name__)
MAX_AGE_MINUTES = 15
@@ -171,6 +209,9 @@ def get_stuck_static_cohort_candidates_queryset() -> QuerySet:
(initial population never completed)
- OR is_calculating=True AND last_calculation > 1 hour ago
(re-population never completed)
+ - AND it has not errored within the last hour. A population task stamps last_error_at when
+ it schedules a retry, and reset_stuck_cohorts stamps it when it re-dispatches, so a recent
+ error means the run is alive and resetting it would dispatch a duplicate population.
"""
one_hour_ago = timezone.now() - relativedelta(hours=1)
return (
@@ -184,6 +225,7 @@ def get_stuck_static_cohort_candidates_queryset() -> QuerySet:
Q(last_calculation__isnull=True, created_at__lte=one_hour_ago)
| Q(last_calculation__lte=one_hour_ago, last_calculation__isnull=False)
)
+ .filter(Q(last_error_at__isnull=True) | Q(last_error_at__lte=one_hour_ago))
.filter(
# Only fetch cohorts that have a retriggerable population source
# (HogQL query or filter criteria). Excludes CSV-upload cohorts
@@ -523,7 +565,7 @@ def calculate_cohort_ch(
# 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):
+ if _is_final_attempt(self, isinstance(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.
@@ -554,33 +596,103 @@ def calculate_cohort_ch(
# 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),
+ will_retry=lambda err: not _is_final_attempt(self, isinstance(err, COHORT_RECALCULATION_TRANSIENT_ERRORS)),
)
-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.
+def _is_transient_population_error(err: BaseException) -> bool:
+ # Static population runs the same ORM statements as recalculation, so it shares the Postgres
+ # legs: a pooler blip between two personhog batches must not be recorded as a permanent failure.
+ return isinstance(err, STATIC_POPULATION_TRANSIENT_ERRORS) or is_transient_rpc_error(
+ err, codes=STATIC_POPULATION_RETRYABLE_RPC_CODES
+ )
- 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, retryable_errors):
+
+def _is_final_attempt(task: Task, retryable: bool) -> bool:
+ """Whether the caller must finalize failure state instead of leaving it for a retry."""
+ if not retryable:
return True
if task.request.called_directly:
return True
return task.max_retries is not None and (task.request.retries or 0) >= task.max_retries
+def _schedule_population_retry(
+ task: Task, cohort_id: int, err: Exception, *, team_id: int | None, kwargs: dict[str, Any] | None = None
+) -> Retry:
+ """Schedule the next attempt and return the Retry for the caller to raise.
+
+ Returns instead of raising so the caller can note that a retry is pending before it raises.
+ When the broker publish fails, Celery raises Reject from here instead of returning, and the
+ caller then finalizes the failure like any other terminal outcome. Takes the id rather than the
+ cohort because the first read of the task is itself retryable: CONN_MAX_AGE is 0, so a pooler
+ blip lands on the connection that read opens. ``kwargs`` carries progress the next attempt can
+ resume from.
+ """
+ retries = task.request.retries or 0
+ countdown = get_exponential_backoff_interval(
+ factor=STATIC_POPULATION_RETRY_BACKOFF_SECONDS,
+ retries=retries,
+ maximum=STATIC_POPULATION_RETRY_BACKOFF_MAX_SECONDS,
+ full_jitter=True,
+ )
+ # reset_stuck_cohorts treats a static cohort that errored within the hour as alive. Without the
+ # stamp it reads the backoff window as a stalled run and dispatches a duplicate population.
+ save_recovery_bookkeeping(
+ lambda: Cohort.objects.filter(pk=cohort_id).update(last_error_at=timezone.now()),
+ cohort_id=cohort_id,
+ team_id=team_id,
+ )
+ error_type = type(err).__name__
+ COHORT_STATIC_POPULATION_RETRIES_COUNTER.labels(task=task.name, error_type=error_type).inc()
+ logger.warning(
+ "static_cohort_population_retry",
+ cohort_id=cohort_id,
+ team_id=team_id,
+ task=task.name,
+ retries=retries,
+ max_retries=task.max_retries,
+ countdown=countdown,
+ error_type=error_type,
+ error=str(err),
+ )
+ # Merge, because task.retry(kwargs=...) replaces the whole set and would drop whatever the
+ # dispatch site passed by keyword.
+ retry_kwargs = {**(task.request.kwargs or {}), **kwargs} if kwargs else None
+ return task.retry(exc=err, countdown=countdown, throw=False, kwargs=retry_kwargs)
+
+
+def _tag_population_queries(task: Task, *, cohort_id: int, team_id: int) -> None:
+ tags = QueryTags(cohort_id=cohort_id, team_id=team_id)
+ if task.request.id:
+ tags.celery_task_id = task.request.id
+ update_tags(tags)
+
+
+def _static_population_obsolete(task: Task, cohort: Cohort) -> bool:
+ """Whether the cohort was deleted or flipped to dynamic while this attempt waited in a backoff.
+
+ A flip enqueues calculate_cohort_ch, which owns is_calculating and count from then on. A late
+ static attempt would clear the flag under that calculation and overwrite count with the static
+ member count, so it must not write anything, including its own final state.
+ """
+ if not cohort.deleted and cohort.is_static:
+ return False
+ logger.info(
+ "static_cohort_population_skipped",
+ cohort_id=cohort.pk,
+ team_id=cohort.team_id,
+ task=task.name,
+ deleted=cohort.deleted,
+ is_static=cohort.is_static,
+ )
+ return True
+
+
@shared_task(
bind=True,
ignore_result=True,
- # Auto-retry transient ClickHouse capacity errors with exponential backoff, matching the
- # dynamic-cohort sibling calculate_cohort_ch. Without this, a brief capacity blip during
- # the person_static_cohort insert leaves the static cohort permanently half-populated.
- autoretry_for=CH_TRANSIENT_ERRORS,
- retry_backoff=60,
- retry_backoff_max=1800,
- max_retries=6,
+ max_retries=STATIC_POPULATION_MAX_RETRIES,
)
@skip_team_scope_audit
def calculate_cohort_from_list(
@@ -596,19 +708,22 @@ def calculate_cohort_from_list(
All new tasks should pass team_id explicitly.
"""
start_time = time.time()
- cohort = Cohort.objects.get(pk=cohort_id)
- if team_id is None:
- team_id = cohort.team_id
-
import_resolution = ImportResolution()
if id_type not in ("distinct_id", "person_id", "email"):
raise ValueError(f"Unsupported id_type: {id_type}")
- # raise_on_error surfaces a batch insert failure instead of swallowing it, so a transient
- # capacity blip propagates and triggers the backed-off retry above. Retries are safe: the
- # insert path dedupes members already in the cohort (ClickHouse excludes existing UUIDs, the
- # InsertCohortMembers RPC dedupes on person id), so re-running the whole list adds no duplicates.
+ cohort: Cohort | None = None
+ processing_error: BaseException | None = None
+ retry: Retry | None = None
+ # Whole-list retries are safe because both stores ignore members already in the cohort.
+ # raise_on_error lets this task distinguish a retryable partial insert from final success.
try:
+ cohort = Cohort.objects.get(pk=cohort_id)
+ if team_id is None:
+ team_id = cohort.team_id
+ if _static_population_obsolete(self, cohort):
+ return
+
if id_type == "distinct_id":
batch_count = cohort.insert_users_by_list(
items, team_id=team_id, raise_on_error=True, import_resolution=import_resolution
@@ -638,171 +753,197 @@ def calculate_cohort_from_list(
unmatched=import_resolution.unmatched,
)
except Exception as err:
- # 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, CH_TRANSIENT_ERRORS):
- cohort._safe_save_cohort_state(team_id=team_id, processing_error=err)
+ processing_error = err
+ if _is_final_attempt(self, _is_transient_population_error(err)):
+ raise
+ retry = _schedule_population_retry(self, cohort_id, err, team_id=team_id)
+ raise retry
+ except BaseException as err:
+ # A run the worker cut short (shutdown, revoke) failed; it must not stay in flight.
+ processing_error = err
raise
+ finally:
+ # The batching helper finalizes success itself and leaves failure to this task, which has
+ # to record it on every exit but a scheduled retry. That includes a retry whose broker
+ # publish failed, where Celery raises Reject in place of Retry.
+ if cohort is not None and processing_error is not None and retry is None:
+ cohort._safe_save_cohort_state(team_id=cohort.team_id, processing_error=processing_error)
logger.warn(
"Cohort {}: {:,} items in {} batches from CSV completed in {:.2f}s".format(
- cohort.pk, len(items), batch_count, (time.time() - start_time)
+ cohort_id, len(items), batch_count, (time.time() - start_time)
)
)
-@shared_task(
- ignore_result=True,
- max_retries=1,
- queue=CeleryQueue.LONG_RUNNING.value,
-)
-@skip_team_scope_audit
-def insert_cohort_from_query(cohort_id: int, team_id: Optional[int] = None) -> None:
- """
- One-time population task for static cohorts created from a HogQL query
- (e.g. duplicating a dynamic cohort as static).
-
- Inserts actors into ClickHouse person_static_cohort, then syncs to Postgres.
+def _populate_static_cohort(
+ task: Task,
+ *,
+ cohort_id: int,
+ team_id: Optional[int],
+ ch_insert_done: bool,
+ insert_actors_into_ch: Callable[..., None],
+ log_prefix: str,
+) -> None:
+ """Run one static population attempt: claim the cohort, fill ClickHouse, then sync Postgres.
- team_id is only optional for backwards compatibility with the old celery task signature.
- All new tasks should pass team_id explicitly.
+ Both population tasks delegate here, so the claim, retry and finalize protocol has one home
+ and cannot drift between them.
"""
- from products.cohorts.backend.models.util import insert_cohort_people_into_pg, insert_cohort_query_actors_into_ch
-
- cohort = Cohort.objects.get(pk=cohort_id)
- if team_id is None:
- team_id = cohort.team_id
- team = Team.objects.get(pk=team_id)
+ from products.cohorts.backend.models.util import insert_cohort_people_into_pg
- logger.info(
- "insert_cohort_from_query_started",
- cohort_id=cohort_id,
- team_id=team_id,
- query=cohort.query,
- )
-
- processing_error = None
+ # The cohort this attempt marked is_calculating. Only that attempt finalizes the flag, so a
+ # skipped or never-started attempt leaves whoever owns it (the API, a newer calculation) alone.
+ claimed: Cohort | None = None
+ processing_error: BaseException | None = None
+ retry: Retry | None = None
try:
+ if team_id is not None:
+ cohort = Cohort.objects.get(pk=cohort_id, team_id=team_id)
+ else:
+ cohort = Cohort.objects.get(pk=cohort_id)
+ team_id = cohort.team_id
+ if _static_population_obsolete(task, cohort):
+ return
+ team = Team.objects.get(pk=team_id)
+ _tag_population_queries(task, cohort_id=cohort_id, team_id=team_id)
+ logger.info(
+ f"{log_prefix}_started",
+ cohort_id=cohort_id,
+ team_id=team_id,
+ query=cohort.query,
+ filters=cohort.filters,
+ )
+
cohort.is_calculating = True
cohort.save(update_fields=["is_calculating"])
+ claimed = cohort
cohort.refresh_from_db()
# The CH insert is idempotent: it excludes person_ids already in the cohort.
# This handles both the retry-after-OOM case (no duplicates) and the
- # add-more-people-via-query case (only new people inserted).
- insert_cohort_query_actors_into_ch(cohort, team=team)
- logger.info(
- "insert_cohort_from_query_ch_complete",
- cohort_id=cohort_id,
- team_id=team_id,
- )
+ # add-more-people-via-query case (only new people inserted). A retry whose earlier attempt
+ # finished this phase skips it, because re-evaluating the source query costs the same hours
+ # again and inserts nothing.
+ if not ch_insert_done:
+ insert_actors_into_ch(cohort, team=team)
+ ch_insert_done = True
+ logger.info(
+ f"{log_prefix}_ch_complete",
+ cohort_id=cohort_id,
+ team_id=team_id,
+ )
- # PG sync is already resumable: _insert_users_list_with_batching checks
- # existing_person_ids each batch and skips people already in the cohort.
+ # Re-running the sync is safe because InsertCohortMembers ignores existing membership.
insert_cohort_people_into_pg(cohort, team_id=team_id)
logger.info(
- "insert_cohort_from_query_pg_complete",
+ f"{log_prefix}_pg_complete",
cohort_id=cohort_id,
team_id=team_id,
)
except Exception as err:
processing_error = err
+ if not _is_final_attempt(task, _is_transient_population_error(err)):
+ retry = _schedule_population_retry(
+ task, cohort_id, err, team_id=team_id, kwargs={"ch_insert_done": ch_insert_done}
+ )
+ raise retry
logger.exception(
- "insert_cohort_from_query_failed",
+ f"{log_prefix}_failed",
cohort_id=cohort_id,
team_id=team_id,
error=str(err),
)
- # ExposedHogQLError means the user's query is invalid — that's a validation
- # error, not a system bug, so don't report it to error tracking. The failure is
- # still recorded on the cohort's errors_calculating state in the finally block.
+ # ExposedHogQLError is a user validation failure, so do not send it to error tracking.
if not isinstance(err, ExposedHogQLError):
capture_exception()
- if settings.DEBUG:
- raise
+ except BaseException as err:
+ # A run the worker cut short (shutdown, revoke) failed; it must not be saved as a success.
+ processing_error = err
+ raise
finally:
- cohort._safe_save_cohort_state(team_id=team_id, processing_error=processing_error)
- cohort.refresh_from_db(fields=["is_calculating", "errors_calculating"])
- logger.info(
- "insert_cohort_from_query_finished",
- cohort_id=cohort_id,
- team_id=team_id,
- is_calculating=cohort.is_calculating,
- errors_calculating=cohort.errors_calculating,
- )
+ # Every exit but a scheduled retry finalizes state, so a retry whose broker publish failed
+ # (Celery raises Reject in place of Retry) records the failure instead of stranding the
+ # cohort in flight. A scheduled retry keeps is_calculating set for the next attempt.
+ if claimed is not None and retry is None:
+ claimed._safe_save_cohort_state(team_id=claimed.team_id, processing_error=processing_error)
+ claimed.refresh_from_db(fields=["is_calculating", "errors_calculating"])
+ logger.info(
+ f"{log_prefix}_finished",
+ cohort_id=cohort_id,
+ team_id=claimed.team_id,
+ is_calculating=claimed.is_calculating,
+ errors_calculating=claimed.errors_calculating,
+ )
+ if settings.DEBUG and processing_error is not None:
+ raise processing_error
@shared_task(
+ bind=True,
ignore_result=True,
- max_retries=1,
+ max_retries=STATIC_POPULATION_MAX_RETRIES,
queue=CeleryQueue.LONG_RUNNING.value,
+ soft_time_limit=STATIC_POPULATION_SOFT_TIME_LIMIT_SECONDS,
)
@skip_team_scope_audit
-def insert_cohort_from_filters(cohort_id: int, team_id: Optional[int] = None) -> None:
- """
- One-time population task for static cohorts created from saved cohort criteria.
+def insert_cohort_from_query(
+ self: Task, cohort_id: int, team_id: Optional[int] = None, ch_insert_done: bool = False
+) -> None:
"""
- from products.cohorts.backend.models.util import insert_cohort_filter_actors_into_ch, insert_cohort_people_into_pg
+ One-time population task for static cohorts created from a HogQL query
+ (e.g. duplicating a dynamic cohort as static).
- if team_id is not None:
- cohort = Cohort.objects.get(pk=cohort_id, team_id=team_id)
- else:
- cohort = Cohort.objects.get(pk=cohort_id)
- team_id = cohort.team_id
- team = Team.objects.get(pk=team_id)
+ Inserts actors into ClickHouse person_static_cohort, then syncs to Postgres.
- logger.info(
- "insert_cohort_from_filters_started",
+ team_id is only optional for backwards compatibility with the old celery task signature.
+ All new tasks should pass team_id explicitly. Only a retry sets ch_insert_done.
+ """
+ from products.cohorts.backend.models.util import insert_cohort_query_actors_into_ch
+
+ _populate_static_cohort(
+ self,
cohort_id=cohort_id,
team_id=team_id,
- filters=cohort.filters,
+ ch_insert_done=ch_insert_done,
+ insert_actors_into_ch=insert_cohort_query_actors_into_ch,
+ log_prefix="insert_cohort_from_query",
)
- processing_error = None
- try:
- cohort.is_calculating = True
- cohort.save(update_fields=["is_calculating"])
- insert_cohort_filter_actors_into_ch(cohort, team=team)
- logger.info(
- "insert_cohort_from_filters_ch_complete",
- cohort_id=cohort_id,
- team_id=team_id,
- )
+@shared_task(
+ bind=True,
+ ignore_result=True,
+ max_retries=STATIC_POPULATION_MAX_RETRIES,
+ queue=CeleryQueue.LONG_RUNNING.value,
+ soft_time_limit=STATIC_POPULATION_SOFT_TIME_LIMIT_SECONDS,
+)
+@skip_team_scope_audit
+def insert_cohort_from_filters(
+ self: Task, cohort_id: int, team_id: Optional[int] = None, ch_insert_done: bool = False
+) -> None:
+ """
+ One-time population task for static cohorts created from saved cohort criteria.
- insert_cohort_people_into_pg(cohort, team_id=team_id)
- logger.info(
- "insert_cohort_from_filters_pg_complete",
- cohort_id=cohort_id,
- team_id=team_id,
- )
- except Exception as err:
- processing_error = err
- logger.exception(
- "insert_cohort_from_filters_failed",
- cohort_id=cohort_id,
- team_id=team_id,
- error=str(err),
- )
- capture_exception()
- if settings.DEBUG:
- raise
- finally:
- cohort._safe_save_cohort_state(team_id=team_id, processing_error=processing_error)
- cohort.refresh_from_db(fields=["is_calculating", "errors_calculating"])
- logger.info(
- "insert_cohort_from_filters_finished",
- cohort_id=cohort_id,
- team_id=team_id,
- is_calculating=cohort.is_calculating,
- errors_calculating=cohort.errors_calculating,
- )
+ Only a retry sets ch_insert_done.
+ """
+ from products.cohorts.backend.models.util import insert_cohort_filter_actors_into_ch
+
+ _populate_static_cohort(
+ self,
+ cohort_id=cohort_id,
+ team_id=team_id,
+ ch_insert_done=ch_insert_done,
+ insert_actors_into_ch=insert_cohort_filter_actors_into_ch,
+ log_prefix="insert_cohort_from_filters",
+ )
-# No task-level retry: transient failures are already retried per page with backoff
-# inside get_cohort_actors_for_feature_flag, and by the time an exception propagates
-# here the task has recorded final error state (calculation history, errors_calculating,
-# is_calculating=False) — a Celery retry after that would contradict the recorded state.
+# No task-level retry. The per-page backoff inside get_cohort_actors_for_feature_flag covers the
+# call to the flags service and nothing else, so a transient personhog or ClickHouse error from the
+# member insert is terminal here, unlike in the sibling static population tasks. By the time any
+# exception propagates to this task, get_cohort_actors_for_feature_flag has recorded final error
+# state (calculation history, errors_calculating, is_calculating=False), and a Celery retry would
+# contradict what the cohort already reports.
# Runs on the long-running queue (like the sibling cohort tasks) so a large paging run
# can't clog the default workers, with a generous soft limit as a backstop ceiling.
# SoftTimeLimitExceeded subclasses Exception, so get_cohort_actors_for_feature_flag's
diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.py
index 68dc535af2d4..7577b088e7ca 100644
--- a/posthog/tasks/test/test_calculate_cohort.py
+++ b/posthog/tasks/test/test_calculate_cohort.py
@@ -9,7 +9,9 @@ from django.db import InterfaceError, OperationalError
from django.test import override_settings
from django.utils import timezone
-from celery.exceptions import Retry
+import grpc
+from celery import Task
+from celery.exceptions import Reject, Retry, SoftTimeLimitExceeded
from dateutil.relativedelta import relativedelta
from parameterized import parameterized
@@ -27,11 +29,13 @@ from posthog.tasks.calculate_cohort import (
MAX_AGE_MINUTES,
MAX_ERRORS_CALCULATING,
MAX_STUCK_COHORTS_TO_RESET,
+ STATIC_POPULATION_MAX_RETRIES,
calculate_cohort_ch,
calculate_cohort_from_list,
enqueue_cohorts_to_calculate,
increment_version_and_enqueue_calculate_cohort,
insert_cohort_from_filters,
+ insert_cohort_from_query,
reset_stuck_cohorts,
trigger_cohort_backfill_run_task,
update_cohort_metrics,
@@ -42,7 +46,7 @@ from products.cohorts.backend.backfill.runs import BackfillRefusalReason
from products.cohorts.backend.backfill.sizing import PersonSeedEstimate
from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillRun
from products.cohorts.backend.models.cohort import Cohort, CohortType
-from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_ids
+from products.cohorts.backend.models.util import count_cohort_members, insert_static_cohort, list_cohort_member_ids
MISSING_COHORT_ID = 12345
@@ -61,6 +65,18 @@ BACKFILL_TASK_SETTINGS = {
}
+def _rpc_error(code: grpc.StatusCode) -> grpc.RpcError:
+ error = grpc.RpcError()
+ error.code = MagicMock(return_value=code)
+ return error
+
+
+QUERY_CH_INSERT_PATH = "products.cohorts.backend.models.util.insert_cohort_query_actors_into_ch"
+FILTERS_CH_INSERT_PATH = "products.cohorts.backend.models.util.insert_cohort_filter_actors_into_ch"
+PG_SYNC_PATH = "products.cohorts.backend.models.util.insert_cohort_people_into_pg"
+COHORT_READ_PATH = "posthog.tasks.calculate_cohort.Cohort.objects.get"
+
+
def calculate_cohort_test_factory(event_factory: Callable, person_factory: Callable): # type: ignore
class TestCalculateCohort(APIBaseTest):
@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")
@@ -1415,8 +1431,6 @@ class TestCohortCalculationTasks(APIBaseTest):
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_query
-
cohort = Cohort.objects.create(
team_id=self.team.pk,
name="test_query_cohort",
@@ -1451,8 +1465,6 @@ class TestCohortCalculationTasks(APIBaseTest):
def test_insert_cohort_from_query_only_captures_system_errors(
self, _name: str, raised: Exception, expected_capture_calls: int
) -> None:
- from posthog.tasks.calculate_cohort import insert_cohort_from_query
-
cohort = Cohort.objects.create(
team_id=self.team.pk,
name="test_query_cohort",
@@ -1474,6 +1486,269 @@ class TestCohortCalculationTasks(APIBaseTest):
self.assertFalse(cohort.is_calculating, "Cohort should not be in calculating state")
self.assertGreater(cohort.errors_calculating, 0, "Failure should be recorded regardless of error type")
+ @parameterized.expand(
+ [
+ ("query", insert_cohort_from_query, QUERY_CH_INSERT_PATH),
+ ("filters", insert_cohort_from_filters, FILTERS_CH_INSERT_PATH),
+ ]
+ )
+ @override_settings(DEBUG=False)
+ @patch("products.cohorts.backend.models.util.insert_cohort_members")
+ def test_static_population_records_personhog_sync_failure(
+ self, _name: str, task: Task, ch_insert_path: str, mock_insert_members: MagicMock
+ ) -> None:
+ person = create_person(team=self.team, distinct_ids=["personhog-sync-failure"])
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="static cohort",
+ is_static=True,
+ query={"kind": "HogQLQuery", "query": "SELECT id FROM persons"},
+ )
+ insert_static_cohort([person.uuid], cohort.pk, team_id=self.team.pk)
+ mock_insert_members.side_effect = ValueError("personhog unavailable")
+
+ with patch(ch_insert_path):
+ task(cohort.id, self.team.pk)
+
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.errors_calculating, 1)
+ self.assertFalse(cohort.is_calculating)
+ self.assertIsNone(cohort.last_calculation)
+
+ @parameterized.expand(
+ [
+ (
+ "query_personhog_unavailable",
+ insert_cohort_from_query,
+ QUERY_CH_INSERT_PATH,
+ PG_SYNC_PATH,
+ lambda: _rpc_error(grpc.StatusCode.UNAVAILABLE),
+ ),
+ (
+ "filters_personhog_unavailable",
+ insert_cohort_from_filters,
+ FILTERS_CH_INSERT_PATH,
+ PG_SYNC_PATH,
+ lambda: _rpc_error(grpc.StatusCode.UNAVAILABLE),
+ ),
+ (
+ "query_personhog_shedding_load",
+ insert_cohort_from_query,
+ QUERY_CH_INSERT_PATH,
+ PG_SYNC_PATH,
+ lambda: _rpc_error(grpc.StatusCode.RESOURCE_EXHAUSTED),
+ ),
+ (
+ "query_personhog_query_error",
+ insert_cohort_from_query,
+ QUERY_CH_INSERT_PATH,
+ PG_SYNC_PATH,
+ lambda: _rpc_error(grpc.StatusCode.INTERNAL),
+ ),
+ (
+ "query_postgres_connection_dropped",
+ insert_cohort_from_query,
+ QUERY_CH_INSERT_PATH,
+ PG_SYNC_PATH,
+ lambda: OperationalError("server closed the connection unexpectedly"),
+ ),
+ (
+ "query_postgres_dropped_on_first_read",
+ insert_cohort_from_query,
+ QUERY_CH_INSERT_PATH,
+ COHORT_READ_PATH,
+ lambda: OperationalError("server closed the connection unexpectedly"),
+ ),
+ (
+ "query_ran_past_the_soft_time_limit",
+ insert_cohort_from_query,
+ QUERY_CH_INSERT_PATH,
+ PG_SYNC_PATH,
+ lambda: SoftTimeLimitExceeded(),
+ ),
+ ]
+ )
+ def test_static_population_retries_a_transient_failure(
+ self,
+ _name: str,
+ task: Task,
+ ch_insert_path: str,
+ failing_path: str,
+ error_factory: Callable[[], Exception],
+ ) -> None:
+ # The enqueue site flips is_calculating before it dispatches, so a retry pending on the first
+ # read must leave that flag alone rather than clear it.
+ cohort = Cohort.objects.create(team=self.team, name="static cohort", is_static=True, is_calculating=True)
+ task.push_request(retries=0, called_directly=False, is_eager=True)
+ try:
+ with (
+ patch(ch_insert_path),
+ patch(failing_path, side_effect=error_factory()),
+ self.assertRaises(Retry),
+ ):
+ task.run(cohort.id, self.team.pk)
+ finally:
+ task.pop_request()
+
+ cohort.refresh_from_db()
+ self.assertTrue(cohort.is_calculating)
+ self.assertEqual(cohort.errors_calculating, 0)
+ self.assertIsNone(cohort.last_calculation)
+ self.assertIsNotNone(cohort.last_error_at)
+
+ @parameterized.expand(
+ [
+ ("query", insert_cohort_from_query, QUERY_CH_INSERT_PATH),
+ ("filters", insert_cohort_from_filters, FILTERS_CH_INSERT_PATH),
+ ]
+ )
+ def test_static_population_records_a_transient_failure_once_retries_run_out(
+ self, _name: str, task: Task, ch_insert_path: str
+ ) -> None:
+ cohort = Cohort.objects.create(team=self.team, name="static cohort", is_static=True, is_calculating=True)
+ task.push_request(retries=STATIC_POPULATION_MAX_RETRIES, called_directly=False, is_eager=True)
+ try:
+ with (
+ patch(ch_insert_path),
+ patch(PG_SYNC_PATH, side_effect=_rpc_error(grpc.StatusCode.UNAVAILABLE)),
+ ):
+ task.run(cohort.id, self.team.pk)
+ finally:
+ task.pop_request()
+
+ cohort.refresh_from_db()
+ self.assertFalse(cohort.is_calculating)
+ self.assertEqual(cohort.errors_calculating, 1)
+ self.assertIsNone(cohort.last_calculation)
+ self.assertIsNotNone(cohort.last_error_at)
+
+ @parameterized.expand(
+ [
+ ("query", insert_cohort_from_query, QUERY_CH_INSERT_PATH),
+ ("filters", insert_cohort_from_filters, FILTERS_CH_INSERT_PATH),
+ ]
+ )
+ def test_static_population_retry_skips_a_finished_clickhouse_insert(
+ self, _name: str, task: Task, ch_insert_path: str
+ ) -> None:
+ # Re-evaluating the source query costs the same hours again and inserts nothing, so an
+ # attempt that only failed on the Postgres sync has to resume at that sync.
+ cohort = Cohort.objects.create(team=self.team, name="static cohort", is_static=True)
+ task.push_request(retries=0, called_directly=False, is_eager=True)
+ try:
+ with (
+ patch(ch_insert_path),
+ patch(PG_SYNC_PATH, side_effect=_rpc_error(grpc.StatusCode.UNAVAILABLE)),
+ self.assertRaises(Retry) as scheduled,
+ ):
+ task.run(cohort.id, self.team.pk)
+
+ with patch(ch_insert_path) as mock_insert_ch, patch(PG_SYNC_PATH):
+ task.run(cohort.id, self.team.pk, **scheduled.exception.sig.kwargs)
+ finally:
+ task.pop_request()
+
+ mock_insert_ch.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("query_flipped_to_dynamic", insert_cohort_from_query, QUERY_CH_INSERT_PATH, {"is_static": False}),
+ ("filters_flipped_to_dynamic", insert_cohort_from_filters, FILTERS_CH_INSERT_PATH, {"is_static": False}),
+ ("query_deleted", insert_cohort_from_query, QUERY_CH_INSERT_PATH, {"is_static": True, "deleted": True}),
+ ]
+ )
+ def test_static_population_skips_an_obsolete_cohort(
+ self, _name: str, task: Task, ch_insert_path: str, cohort_state: dict[str, bool]
+ ) -> None:
+ # Flipping a static cohort to dynamic hands is_calculating to calculate_cohort_ch. An attempt
+ # that wakes from its backoff afterwards must neither write members nor finalize that flag.
+ cohort = Cohort.objects.create(team=self.team, name="static cohort", is_calculating=True, **cohort_state)
+
+ with patch(ch_insert_path) as mock_insert_ch, patch(PG_SYNC_PATH) as mock_sync:
+ task(cohort.id, self.team.pk)
+
+ mock_insert_ch.assert_not_called()
+ mock_sync.assert_not_called()
+ cohort.refresh_from_db()
+ self.assertTrue(cohort.is_calculating)
+ self.assertIsNone(cohort.last_calculation)
+
+ @parameterized.expand(
+ [
+ ("errored_within_the_hour", relativedelta(minutes=10), False),
+ ("errored_over_an_hour_ago", relativedelta(hours=2), True),
+ ]
+ )
+ @patch("posthog.tasks.calculate_cohort.insert_cohort_from_query")
+ def test_reset_stuck_static_cohorts_honors_a_recent_error(
+ self, _name: str, error_age: relativedelta, expect_reset: bool, mock_insert_cohort_from_query: MagicMock
+ ) -> None:
+ # A population task stamps last_error_at when it schedules a retry, so within the hour the
+ # cohort sits in a backoff window, not stuck. Resetting it would dispatch a duplicate.
+ now = timezone.now()
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="static in retry backoff",
+ is_calculating=True,
+ is_static=True,
+ last_error_at=now - error_age,
+ query={"kind": "HogQLQuery", "query": "SELECT id FROM persons"},
+ )
+ Cohort.objects.filter(pk=cohort.pk).update(created_at=now - relativedelta(hours=2))
+
+ reset_stuck_cohorts()
+
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.is_calculating, not expect_reset)
+ self.assertEqual(cohort.errors_calculating, 1 if expect_reset else 0)
+ self.assertEqual(mock_insert_cohort_from_query.delay.called, expect_reset)
+
+ @parameterized.expand(
+ [
+ ("query", insert_cohort_from_query, QUERY_CH_INSERT_PATH),
+ ("filters", insert_cohort_from_filters, FILTERS_CH_INSERT_PATH),
+ ]
+ )
+ def test_static_population_records_failure_when_retry_cannot_be_published(
+ self, _name: str, task: Task, ch_insert_path: str
+ ) -> None:
+ cohort = Cohort.objects.create(team=self.team, name="static cohort", is_static=True)
+ task.push_request(retries=0, called_directly=False, is_eager=True)
+ try:
+ with (
+ patch(ch_insert_path),
+ patch(PG_SYNC_PATH, side_effect=_rpc_error(grpc.StatusCode.UNAVAILABLE)),
+ patch.object(task, "retry", side_effect=Reject("broker unavailable", requeue=False)),
+ self.assertRaises(Reject),
+ ):
+ task.run(cohort.id, self.team.pk)
+ finally:
+ task.pop_request()
+
+ cohort.refresh_from_db()
+ self.assertFalse(cohort.is_calculating)
+ self.assertEqual(cohort.errors_calculating, 1)
+
+ @parameterized.expand(
+ [
+ ("query", insert_cohort_from_query, QUERY_CH_INSERT_PATH),
+ ("filters", insert_cohort_from_filters, FILTERS_CH_INSERT_PATH),
+ ]
+ )
+ def test_static_population_records_failure_when_the_worker_cuts_the_run_short(
+ self, _name: str, task: Task, ch_insert_path: str
+ ) -> None:
+ # A shutdown leaves the cohort half-written, so it must not be finalized as calculated.
+ cohort = Cohort.objects.create(team=self.team, name="static cohort", is_static=True)
+
+ with patch(ch_insert_path, side_effect=SystemExit("worker shutdown")), self.assertRaises(SystemExit):
+ task(cohort.id, self.team.pk)
+
+ cohort.refresh_from_db()
+ self.assertFalse(cohort.is_calculating)
+ self.assertEqual(cohort.errors_calculating, 1)
+ self.assertIsNone(cohort.last_calculation)
+
def test_insert_cohort_from_filters_count_updated_on_exception(self) -> None:
cohort = Cohort.objects.create(
team_id=self.team.pk,
@@ -1659,28 +1934,56 @@ class TestCalculateCohortFromListRetries(APIBaseTest):
@parameterized.expand(
[
- ("retries_exhausted", ClickHouseAtCapacity, calculate_cohort_from_list.max_retries, False),
- ("called_directly", ClickHouseAtCapacity, 0, True),
- ("not_retryable", ValueError, 0, False),
+ (
+ "clickhouse_retries_exhausted",
+ "products.cohorts.backend.models.util.insert_static_cohort",
+ ClickHouseAtCapacity,
+ calculate_cohort_from_list.max_retries,
+ False,
+ ),
+ (
+ "clickhouse_called_directly",
+ "products.cohorts.backend.models.util.insert_static_cohort",
+ ClickHouseAtCapacity,
+ 0,
+ True,
+ ),
+ (
+ "not_retryable",
+ "products.cohorts.backend.models.util.insert_static_cohort",
+ ValueError,
+ 0,
+ False,
+ ),
+ (
+ "personhog_retries_exhausted",
+ "products.cohorts.backend.models.util.insert_cohort_members",
+ lambda: _rpc_error(grpc.StatusCode.UNAVAILABLE),
+ calculate_cohort_from_list.max_retries,
+ False,
+ ),
+ (
+ "personhog_not_retryable",
+ "products.cohorts.backend.models.util.insert_cohort_members",
+ lambda: _rpc_error(grpc.StatusCode.INVALID_ARGUMENT),
+ 0,
+ False,
+ ),
]
)
- @patch("products.cohorts.backend.models.util.insert_static_cohort")
def test_records_failure_when_nothing_will_retry(
self,
_name: str,
- error_class: type[Exception],
+ insert_path: str,
+ error_factory: Callable[[], Exception],
retries: int,
called_directly: bool,
- mock_insert_ch: MagicMock,
) -> None:
- # raise_on_error hands terminal-state finalization to the task, so whenever no retry
- # follows, the task itself has to clear is_calculating and bump errors_calculating.
- # Otherwise the cohort is stranded looking in-flight forever with no recorded error.
- mock_insert_ch.side_effect = error_class("boom")
+ error = error_factory()
create_person(team=self.team, distinct_ids=["user123"])
cohort = self._create_static_cohort()
- with self.assertRaises(error_class):
+ with patch(insert_path, side_effect=error), self.assertRaises(type(error)):
self._run_task(cohort, retries=retries, called_directly=called_directly)
cohort.refresh_from_db()
@@ -1688,31 +1991,102 @@ class TestCalculateCohortFromListRetries(APIBaseTest):
self.assertEqual(cohort.errors_calculating, 1)
self.assertIsNotNone(cohort.last_error_at)
- @patch("products.cohorts.backend.models.util.insert_static_cohort")
- def test_leaves_state_untouched_while_retries_remain(self, mock_insert_ch: MagicMock) -> None:
- # A transient failure with attempts left belongs to the pending autoretry, so recording it
- # now would show a cohort that is still being retried as errored and no longer calculating.
- # Celery raising Retry rather than the original error is what confirms one was scheduled.
- mock_insert_ch.side_effect = ClickHouseAtCapacity()
+ @parameterized.expand(
+ [
+ (
+ "clickhouse",
+ "products.cohorts.backend.models.util.insert_static_cohort",
+ ClickHouseAtCapacity,
+ ),
+ (
+ "personhog",
+ "products.cohorts.backend.models.util.insert_cohort_members",
+ lambda: _rpc_error(grpc.StatusCode.UNAVAILABLE),
+ ),
+ (
+ "postgres_on_first_read",
+ COHORT_READ_PATH,
+ lambda: OperationalError("server closed the connection unexpectedly"),
+ ),
+ ]
+ )
+ def test_leaves_state_untouched_while_retries_remain(
+ self, _name: str, insert_path: str, error_factory: Callable[[], Exception]
+ ) -> None:
create_person(team=self.team, distinct_ids=["user123"])
cohort = self._create_static_cohort()
- with self.assertRaises(Retry):
+ with patch(insert_path, side_effect=error_factory()), self.assertRaises(Retry):
self._run_task(cohort, retries=0, called_directly=False)
cohort.refresh_from_db()
self.assertTrue(cohort.is_calculating)
self.assertEqual(cohort.errors_calculating, 0)
+ self.assertIsNotNone(cohort.last_error_at)
+
+ def test_skips_a_cohort_flipped_to_dynamic(self) -> None:
+ create_person(team=self.team, distinct_ids=["user123"])
+ cohort = self._create_static_cohort()
+ Cohort.objects.filter(pk=cohort.pk).update(is_static=False)
+
+ with patch("products.cohorts.backend.models.util.insert_static_cohort") as mock_insert_ch:
+ self._run_task(cohort, retries=0, called_directly=False)
+
+ mock_insert_ch.assert_not_called()
+ cohort.refresh_from_db()
+ self.assertTrue(cohort.is_calculating)
+ self.assertEqual(count_cohort_members(cohort.team_id, cohort.pk), 0)
+
+ def test_records_failure_when_the_worker_cuts_the_run_short(self) -> None:
+ create_person(team=self.team, distinct_ids=["user123"])
+ cohort = self._create_static_cohort()
+
+ with (
+ patch("products.cohorts.backend.models.util.insert_static_cohort", side_effect=SystemExit("shutdown")),
+ self.assertRaises(SystemExit),
+ ):
+ self._run_task(cohort, retries=0, called_directly=False)
- @patch("products.cohorts.backend.models.util.insert_static_cohort")
- def test_retry_after_transient_failure_completes_the_cohort(self, mock_insert_ch: MagicMock) -> None:
- # What the retry buys: the attempt that follows a capacity blip populates every member and
- # finalizes clean state, and re-running the whole list adds no duplicate members.
- mock_insert_ch.side_effect = [ClickHouseAtCapacity(), None]
+ cohort.refresh_from_db()
+ self.assertFalse(cohort.is_calculating)
+ self.assertEqual(cohort.errors_calculating, 1)
+
+ def test_records_failure_when_retry_cannot_be_published(self) -> None:
+ create_person(team=self.team, distinct_ids=["user123"])
+ cohort = self._create_static_cohort()
+
+ with (
+ patch("products.cohorts.backend.models.util.insert_static_cohort", side_effect=ClickHouseAtCapacity()),
+ patch.object(calculate_cohort_from_list, "retry", side_effect=Reject("broker unavailable", requeue=False)),
+ self.assertRaises(Reject),
+ ):
+ self._run_task(cohort, retries=0, called_directly=False)
+
+ cohort.refresh_from_db()
+ self.assertFalse(cohort.is_calculating)
+ self.assertEqual(cohort.errors_calculating, 1)
+
+ @parameterized.expand(
+ [
+ (
+ "clickhouse",
+ "products.cohorts.backend.models.util.insert_static_cohort",
+ ClickHouseAtCapacity,
+ ),
+ (
+ "personhog",
+ "products.cohorts.backend.models.util.insert_cohort_members",
+ lambda: _rpc_error(grpc.StatusCode.UNAVAILABLE),
+ ),
+ ]
+ )
+ def test_retry_after_transient_failure_completes_the_cohort(
+ self, _name: str, insert_path: str, error_factory: Callable[[], Exception]
+ ) -> None:
create_person(team=self.team, distinct_ids=["user123"])
cohort = self._create_static_cohort()
- with self.assertRaises(Retry):
+ with patch(insert_path, side_effect=error_factory()), self.assertRaises(Retry):
self._run_task(cohort, retries=0, called_directly=False)
self._run_task(cohort, retries=1, called_directly=False)
diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.py
index 1abac1b31692..b3761c30f4aa 100644
--- a/products/cohorts/backend/models/util.py
+++ b/products/cohorts/backend/models/util.py
@@ -1176,7 +1176,7 @@ def insert_cohort_filter_actors_into_ch(cohort: Cohort, *, team: Team):
insert_actors_into_cohort_by_query(cohort, query, params, context, team_id=team.id)
-def insert_cohort_people_into_pg(cohort: Cohort, *, team_id: int):
+def insert_cohort_people_into_pg(cohort: Cohort, *, team_id: int) -> None:
from posthog.helpers.batch_iterators import CursorBatchIterator
tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
@@ -1205,7 +1205,11 @@ def insert_cohort_people_into_pg(cohort: Cohort, *, team_id: int):
batch_iterator = CursorBatchIterator(
fetch_batch, CH_PAGE_SIZE, initial_cursor="00000000-0000-0000-0000-000000000000"
)
- cohort._insert_users_list_with_batching(batch_iterator, insert_in_clickhouse=False, team_id=team_id)
+ # raise_on_error hands a partial sync to the caller instead of reporting success, which is
+ # what lets the population tasks retry it.
+ cohort._insert_users_list_with_batching(
+ batch_iterator, insert_in_clickhouse=False, team_id=team_id, raise_on_error=True
+ )
# ── Cohort membership operations (Postgres / personhog) ───────────────