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): reset stuck static cohorts without a population source (#116532)

Phil Haack7a7a916ff019
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 823060cb9bb7..3526399ede80 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -105,6 +105,7 @@ from products.cohorts.backend.models.dependencies import (
)
from products.cohorts.backend.models.util import (
CohortErrorCode,
+ close_open_population_attempts,
cohort_filters_have_values,
get_all_cohort_dependencies,
get_friendly_error_message,
@@ -1212,6 +1213,10 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
raise ValidationError({"csv": [CSVConfig.ErrorMessages.NO_VALID_IDS]})
logger.info(f"Processing CSV upload for cohort {cohort.pk} with {len(ids)} {id_type}s")
+ # A killed import leaves its history row open. The stuck-cohort sweep resets a cohort whose newest row stays
+ # open past its cutoff. That row stays the newest until the task of this upload starts. A run that is still
+ # alive overwrites this stamp when it finishes.
+ close_open_population_attempts(cohort.pk, finished_at=timezone.now())
calculate_cohort_from_list.delay(
cohort.pk,
ids,
@@ -2625,6 +2630,23 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,
started_at = timezone.now()
start_monotonic = time.monotonic()
eval_errors_count = 0
+ # The stuck-cohort sweep measures a run that has an open history row from the row's start. Without that row, the
+ # sweep measures the run from created_at. That measure also counts the time that the task waited in the queue. A
+ # failed insert must not stop the population. Django then keeps the row unsaved. The save of the outcome inserts it.
+ history = CohortCalculationHistory(
+ team_id=team_id, cohort=cohort, filters=cohort.filters or {}, started_at=started_at
+ )
+ try:
+ history.save()
+ except Exception as err:
+ logger.warning(
+ "cohort_from_feature_flag_history_open_failed",
+ cohort_id=cohort_id,
+ team_id=team_id,
+ flag_key=feature_flag.key,
+ exc_info=True,
+ )
+ capture_exception(err, additional_properties={"cohort_id": cohort_id, "team_id": team_id})
try:
uuids_to_add_to_cohort: list[str] = []
cursor = 0
@@ -2704,15 +2726,10 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,
# store the friendly message; raw exception details (internal URLs, instance
# config) stay in logs and error tracking only. This path only ever populates a
# static cohort, and nothing re-runs one, so the message must not ask for that.
- CohortCalculationHistory.objects.create(
- team_id=team_id,
- cohort=cohort,
- filters=cohort.filters or {},
- started_at=started_at,
- finished_at=timezone.now(),
- error=get_friendly_error_message(error_code, will_retry=False),
- error_code=error_code,
- )
+ history.finished_at = timezone.now()
+ history.error = get_friendly_error_message(error_code, will_retry=False)
+ history.error_code = error_code
+ history.save()
raise
# The save above finalized cohort state, including the recomputed count. Recording the run
@@ -2721,14 +2738,11 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,
# the block above: the population is already committed, so a failure to record it must not
# report a finished run as a failed one.
try:
- CohortCalculationHistory.objects.create(
- team_id=team_id,
- cohort=cohort,
- filters=cohort.filters or {},
- started_at=started_at,
- finished_at=timezone.now(),
- count=cohort.count,
- )
+ history.finished_at = timezone.now()
+ history.count = cohort.count
+ # The full save also clears an INTERRUPTED stamp that the stuck-cohort sweep or a CSV upload wrote while this
+ # run was alive.
+ history.save()
except Exception as err:
logger.warning(
"cohort_from_feature_flag_history_write_failed",
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index fc737091e857..8b2f6952d86e 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -50,9 +50,10 @@ from posthog.test.persons import create_person
from products.access_control.backend.models.access_control import AccessControl
from products.actions.backend.models.action import Action
from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillTrigger
+from products.cohorts.backend.models.calculation_history import CohortCalculationHistory
from products.cohorts.backend.models.cohort import DEFAULT_COHORT_INSERT_BATCH_SIZE, Cohort, CohortType
from products.cohorts.backend.models.dependencies import cohort_backfill_pending_key, find_behavioral_cohorts
-from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_ids
+from products.cohorts.backend.models.util import CohortErrorCode, count_cohort_members, list_cohort_member_ids
from products.exports.backend.api.test.test_exports import TestExportMixin
from products.feature_flags.backend.facade.enums import FlagEvaluationsMode
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -549,6 +550,10 @@ [email protected]
distinct_ids = _cohort_member_distinct_ids(cohort.team_id, cohort)
self.assertEqual(distinct_ids, {"123", "0"})
+ killed_attempt = CohortCalculationHistory.objects.create(
+ team=self.team, cohort=cohort, filters={}, started_at=timezone.now() - timedelta(hours=1)
+ )
+
# Test CSV update
csv_update = SimpleUploadedFile(
"example.csv",
@@ -574,6 +579,9 @@ User ID
# Verify CSV update worked - 456 should now be included
distinct_ids = _cohort_member_distinct_ids(cohort.team_id, cohort)
self.assertIn("456", distinct_ids) # New ID should be included
+ killed_attempt.refresh_from_db()
+ self.assertIsNotNone(killed_attempt.finished_at)
+ self.assertEqual(killed_attempt.error_code, CohortErrorCode.INTERRUPTED)
# Test name-only update without CSV
response = self.client.patch(
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index aa0c07be9a68..d6b76cc9cade 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -4,8 +4,8 @@ from datetime import datetime, timedelta
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.db import InterfaceError, OperationalError, transaction
+from django.db.models import Case, DurationField, ExpressionWrapper, F, OuterRef, Q, QuerySet, Subquery, When
from django.utils import timezone
import grpc
@@ -45,6 +45,7 @@ from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, Import
from products.cohorts.backend.models.util import (
COHORT_STATS_COLLECTION_DELAY_SECONDS,
CohortErrorCode,
+ close_open_population_attempts,
get_all_cohort_dependencies,
get_all_cohort_dependents,
get_clickhouse_query_stats,
@@ -177,6 +178,19 @@ MAX_AGE_MINUTES = 15
MAX_ERRORS_CALCULATING = 20
MAX_STUCK_COHORTS_TO_RESET = 3
MAX_STUCK_STATIC_COHORTS_TO_SCAN = MAX_STUCK_COHORTS_TO_RESET * 10
+MAX_STUCK_SOURCELESS_STATIC_COHORTS_TO_RESET = 30
+# insert_cohort_from_feature_flag stops at the soft limit and records its own failure. The sweep measures a cohort with
+# no history row from created_at. The extra hour covers the time that the task of that cohort waits in the queue.
+# calculate_cohort_from_list has no time limit. The sweep therefore resets a CSV import that runs longer than this. When
+# that import finishes, it rewrites the history row that the sweep closed. It also saves the cohort's calculation state
+# again.
+SOURCELESS_STATIC_COHORT_STUCK_AFTER = timedelta(seconds=STATIC_POPULATION_SOFT_TIME_LIMIT_SECONDS, hours=1)
+
+# The path lookup returns NULL for a missing path. IS NOT NULL turns that NULL into false. exclude() therefore selects
+# exactly the rows that filter() rejects. static_cohort_has_supported_population_source rejects a few shapes that this
+# accepts, such as an empty query object. The sourced sweep in reset_stuck_cohorts resets those after an hour. It does
+# not dispatch them again.
+HAS_STATIC_POPULATION_SOURCE = Q(query__isnull=False) | Q(filters__properties__values__0__isnull=False)
def static_cohort_has_supported_population_source(cohort: Cohort) -> bool:
@@ -230,19 +244,83 @@ def get_stuck_static_cohort_candidates_queryset() -> QuerySet:
| 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(HAS_STATIC_POPULATION_SOURCE)
+ )
+
+
+def get_stuck_sourceless_static_cohort_candidates_queryset(cutoff: datetime) -> QuerySet:
+ newest_attempt = CohortCalculationHistory.objects.filter(cohort=OuterRef("pk")).order_by("-started_at")
+ return (
+ Cohort.objects.filter(is_static=True, is_calculating=True, deleted=False)
+ .exclude(HAS_STATIC_POPULATION_SOURCE)
+ .alias(
+ newest_attempt_started_at=Subquery(newest_attempt.values("started_at")[:1]),
+ newest_attempt_finished_at=Subquery(newest_attempt.values("finished_at")[:1]),
+ )
.filter(
- # Only fetch cohorts that have a retriggerable population source
- # (HogQL query or filter criteria). Excludes CSV-upload cohorts
- # that would always be discarded by the retry logic.
- # This may match old static cohorts with stale filter data that
- # predate criteria-based creation; those are caught and skipped
- # by static_cohort_has_supported_population_source in the loop body.
- Q(query__isnull=False)
- | (Q(filters__has_key="properties") & ~Q(filters__properties={}) & ~Q(filters__properties__values=[]))
+ # A cohort is created when its first population is dispatched. Flag runs and CSV imports open a history row
+ # when their task starts. So a cohort that was never populated and has no history row still waits for its
+ # first task. Its created_at is the dispatch time of that task.
+ # A cohort whose earlier population failed without a history row has errors_calculating above 0. A CSV
+ # re-upload to that cohort writes no row until its task starts. This branch therefore skips that cohort.
+ Q(
+ newest_attempt_started_at__isnull=True,
+ last_calculation__isnull=True,
+ errors_calculating=0,
+ created_at__lte=cutoff,
+ )
+ # A flag run or a CSV import closes its history row on every exit except a kill. A CSV upload also closes
+ # the row that a killed attempt left open. So a re-upload that waits in the queue or in a retry backoff has
+ # a closed newest row. That row does not match.
+ | Q(newest_attempt_started_at__lte=cutoff, newest_attempt_finished_at__isnull=True)
)
)
+def _record_stuck_resets(event: str, cohort_ids: list[int]) -> None:
+ if cohort_ids:
+ COHORT_STUCK_RESETS_COUNTER.inc(len(cohort_ids))
+ logger.warning(event, cohort_ids=cohort_ids, count=len(cohort_ids))
+
+
+def reset_stuck_sourceless_static_cohorts() -> None:
+ # These cohorts have no query or filters to populate from again. A flag cohort is also a snapshot that a later run
+ # would change. So the reset records the failure and never dispatches a population.
+ now = timezone.now()
+ cutoff = now - SOURCELESS_STATIC_COHORT_STUCK_AFTER
+ reset_cohort_ids = []
+ for cohort in get_stuck_sourceless_static_cohort_candidates_queryset(cutoff).order_by(F("created_at").asc())[
+ 0:MAX_STUCK_SOURCELESS_STATIC_COHORTS_TO_RESET
+ ]:
+ with transaction.atomic():
+ # The update repeats the candidate test. It skips a cohort whose run finished after the query above read
+ # it, and a cohort that a user re-uploaded after that read.
+ reset = (
+ get_stuck_sourceless_static_cohort_candidates_queryset(cutoff)
+ .filter(pk=cohort.pk)
+ .update(is_calculating=False, errors_calculating=F("errors_calculating") + 1, last_error_at=now)
+ )
+ if not reset:
+ continue
+
+ # The history tab shows an open row as a run in progress.
+ if not close_open_population_attempts(cohort.pk, finished_at=now, started_before=cutoff):
+ CohortCalculationHistory.objects.create(
+ team_id=cohort.team_id,
+ cohort=cohort,
+ filters=cohort.filters or {},
+ # Only a cohort with no history row gets here. The code that created the cohort also dispatched its
+ # run.
+ started_at=cohort.created_at,
+ finished_at=now,
+ error=get_friendly_error_message(CohortErrorCode.INTERRUPTED, will_retry=False),
+ error_code=CohortErrorCode.INTERRUPTED,
+ )
+ reset_cohort_ids.append(cohort.pk)
+
+ _record_stuck_resets("reset_stuck_sourceless_static_cohorts", reset_cohort_ids)
+
+
def reset_stuck_cohorts() -> None:
# A stuck cohort is a cohort that has is_calculating set to true but the query/task failed and
# the field was never set back to false. These cohorts will never get pick up again for
@@ -308,13 +386,9 @@ def reset_stuck_cohorts() -> None:
if len(retriggered_static_cohort_ids) >= MAX_STUCK_COHORTS_TO_RESET:
break
- if reset_static_cohort_ids:
- COHORT_STUCK_RESETS_COUNTER.inc(len(reset_static_cohort_ids))
- logger.warning(
- "reset_stuck_static_cohorts",
- cohort_ids=reset_static_cohort_ids,
- count=len(reset_static_cohort_ids),
- )
+ _record_stuck_resets("reset_stuck_static_cohorts", reset_static_cohort_ids)
+
+ reset_stuck_sourceless_static_cohorts()
def update_cohort_metrics() -> None:
@@ -1025,7 +1099,7 @@ def insert_cohort_from_filters(
ignore_result=True,
max_retries=0,
queue=CeleryQueue.LONG_RUNNING.value,
- soft_time_limit=4 * 60 * 60,
+ soft_time_limit=STATIC_POPULATION_SOFT_TIME_LIMIT_SECONDS,
)
def insert_cohort_from_feature_flag(cohort_id: int, flag_key: str, team_id: int) -> None:
from posthog.api.cohort import get_cohort_actors_for_feature_flag
diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.py
index e090b5fe9422..555ca3bc5ef6 100644
--- a/posthog/tasks/test/test_calculate_cohort.py
+++ b/posthog/tasks/test/test_calculate_cohort.py
@@ -84,10 +84,22 @@ def _rpc_error(code: grpc.StatusCode) -> grpc.RpcError:
return error
+PERSONS_HOGQL_QUERY = {"kind": "HogQLQuery", "query": "SELECT id FROM persons"}
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"
+PERSON_EMAIL_FILTERS = {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [{"key": "email", "type": "person", "value": "[email protected]"}],
+ }
+ ],
+ }
+}
def calculate_cohort_test_factory(event_factory: Callable, person_factory: Callable): # type: ignore
@@ -590,73 +602,6 @@ def calculate_cohort_test_factory(event_factory: Callable, person_factory: Calla
# Verify insert_cohort_from_query was NOT called
mock_insert_cohort_from_query.delay.assert_not_called()
- @patch("posthog.tasks.calculate_cohort.insert_cohort_from_filters")
- @patch("posthog.tasks.calculate_cohort.logger")
- def test_reset_stuck_static_cohorts_retriggers_filters(
- self, mock_logger: MagicMock, mock_insert_cohort_from_filters: MagicMock
- ) -> None:
- now = timezone.now()
-
- stuck_static_cohort = Cohort.objects.create(
- team_id=self.team.pk,
- name="stuck_static_with_filters",
- last_calculation=None,
- deleted=False,
- is_calculating=True,
- errors_calculating=0,
- is_static=True,
- filters={
- "properties": {
- "type": "AND",
- "values": [
- {
- "type": "AND",
- "values": [{"key": "email", "type": "person", "value": "[email protected]"}],
- }
- ],
- }
- },
- )
- Cohort.objects.filter(pk=stuck_static_cohort.pk).update(created_at=now - relativedelta(hours=2))
-
- reset_stuck_cohorts()
-
- stuck_static_cohort.refresh_from_db()
- self.assertFalse(stuck_static_cohort.is_calculating)
- self.assertEqual(stuck_static_cohort.errors_calculating, 1)
- mock_insert_cohort_from_filters.delay.assert_called_with(stuck_static_cohort.pk, self.team.pk)
-
- @patch("posthog.tasks.calculate_cohort.insert_cohort_from_query")
- @patch("posthog.tasks.calculate_cohort.insert_cohort_from_filters")
- @patch("posthog.tasks.calculate_cohort.logger")
- def test_reset_stuck_static_cohorts_without_retriggerable_source(
- self,
- mock_logger: MagicMock,
- mock_insert_cohort_from_filters: MagicMock,
- mock_insert_cohort_from_query: MagicMock,
- ) -> None:
- now = timezone.now()
-
- stuck_static_cohort = Cohort.objects.create(
- team_id=self.team.pk,
- name="stuck_static_without_source",
- last_calculation=None,
- deleted=False,
- is_calculating=True,
- errors_calculating=0,
- is_static=True,
- filters={"properties": {}},
- )
- Cohort.objects.filter(pk=stuck_static_cohort.pk).update(created_at=now - relativedelta(hours=2))
-
- reset_stuck_cohorts()
-
- stuck_static_cohort.refresh_from_db()
- self.assertFalse(stuck_static_cohort.is_calculating)
- self.assertEqual(stuck_static_cohort.errors_calculating, 1)
- mock_insert_cohort_from_filters.delay.assert_not_called()
- mock_insert_cohort_from_query.delay.assert_not_called()
-
@patch("posthog.tasks.calculate_cohort.increment_version_and_enqueue_calculate_cohort")
@patch("posthog.tasks.calculate_cohort.logger")
def test_enqueue_cohorts_logs_correctly(self, mock_logger: MagicMock, mock_increment: MagicMock) -> None:
@@ -1517,7 +1462,7 @@ class TestCohortCalculationTasks(APIBaseTest):
team=self.team,
name="static cohort",
is_static=True,
- query={"kind": "HogQLQuery", "query": "SELECT id FROM persons"},
+ query=PERSONS_HOGQL_QUERY,
)
insert_static_cohort([person.uuid], cohort.pk, team_id=self.team.pk)
mock_insert_members.side_effect = ValueError("personhog unavailable")
@@ -1768,16 +1713,27 @@ class TestCohortCalculationTasks(APIBaseTest):
@parameterized.expand(
[
- ("errored_within_the_hour", relativedelta(minutes=10), False),
- ("errored_over_an_hour_ago", relativedelta(hours=2), True),
+ ("query_errored_within_the_hour", {"query": PERSONS_HOGQL_QUERY}, relativedelta(minutes=10), False),
+ ("query_errored_over_an_hour_ago", {"query": PERSONS_HOGQL_QUERY}, relativedelta(hours=2), True),
+ ("filters_errored_over_an_hour_ago", {"filters": PERSON_EMAIL_FILTERS}, relativedelta(hours=2), True),
]
)
+ @patch("posthog.tasks.calculate_cohort.insert_cohort_from_filters")
@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
+ self,
+ _name: str,
+ source_fields: dict,
+ error_age: relativedelta,
+ expect_reset: bool,
+ mock_insert_cohort_from_query: MagicMock,
+ mock_insert_cohort_from_filters: 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.
+ mock_population_task = (
+ mock_insert_cohort_from_query if "query" in source_fields else mock_insert_cohort_from_filters
+ )
now = timezone.now()
cohort = Cohort.objects.create(
team=self.team,
@@ -1785,7 +1741,7 @@ class TestCohortCalculationTasks(APIBaseTest):
is_calculating=True,
is_static=True,
last_error_at=now - error_age,
- query={"kind": "HogQLQuery", "query": "SELECT id FROM persons"},
+ **source_fields,
)
Cohort.objects.filter(pk=cohort.pk).update(created_at=now - relativedelta(hours=2))
@@ -1794,7 +1750,121 @@ class TestCohortCalculationTasks(APIBaseTest):
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)
+ self.assertEqual(mock_population_task.delay.called, expect_reset)
+
+ @parameterized.expand(
+ [
+ ("flag_run_killed", None, relativedelta(hours=6), [], None, 0, True),
+ ("flag_run_within_soft_limit", None, relativedelta(hours=4), [], None, 0, False),
+ (
+ "filters_without_values_killed",
+ {"properties": {"type": "AND"}},
+ relativedelta(hours=6),
+ [],
+ None,
+ 0,
+ True,
+ ),
+ (
+ "csv_reupload_killed",
+ {"properties": {}},
+ relativedelta(days=3),
+ [(relativedelta(hours=6), False)],
+ None,
+ 0,
+ True,
+ ),
+ (
+ "csv_reupload_running",
+ {"properties": {}},
+ relativedelta(days=3),
+ [(relativedelta(minutes=10), False)],
+ None,
+ 0,
+ False,
+ ),
+ (
+ "csv_reupload_queued_after_a_finished_attempt",
+ {"properties": {}},
+ relativedelta(days=3),
+ [(relativedelta(days=2), True)],
+ None,
+ 0,
+ False,
+ ),
+ (
+ "csv_reupload_running_after_a_killed_attempt",
+ {"properties": {}},
+ relativedelta(days=3),
+ [(relativedelta(hours=6), False), (relativedelta(minutes=10), False)],
+ None,
+ 0,
+ False,
+ ),
+ (
+ "csv_reupload_queued_to_a_populated_cohort",
+ {"properties": {}},
+ relativedelta(days=3),
+ [],
+ relativedelta(days=2),
+ 0,
+ False,
+ ),
+ ("csv_reupload_queued_to_a_failed_cohort", {"properties": {}}, relativedelta(days=3), [], None, 1, False),
+ ]
+ )
+ @patch("posthog.tasks.calculate_cohort.insert_cohort_from_filters")
+ @patch("posthog.tasks.calculate_cohort.insert_cohort_from_query")
+ def test_reset_stuck_sourceless_static_cohorts(
+ self,
+ _name: str,
+ filters: dict | None,
+ created_age: relativedelta,
+ attempts: list[tuple[relativedelta, bool]],
+ last_calculation_age: relativedelta | None,
+ errors_calculating: int,
+ expect_reset: bool,
+ mock_insert_cohort_from_query: MagicMock,
+ mock_insert_cohort_from_filters: MagicMock,
+ ) -> None:
+ now = timezone.now()
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="static without a population source",
+ is_calculating=True,
+ is_static=True,
+ filters=filters,
+ last_calculation=now - last_calculation_age if last_calculation_age else None,
+ errors_calculating=errors_calculating,
+ )
+ Cohort.objects.filter(pk=cohort.pk).update(created_at=now - created_age)
+ for attempt_age, attempt_finished in attempts:
+ CohortCalculationHistory.objects.create(
+ team=self.team,
+ cohort=cohort,
+ filters={},
+ started_at=now - attempt_age,
+ finished_at=now - attempt_age if attempt_finished else None,
+ )
+
+ reset_stuck_cohorts()
+
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.is_calculating, not expect_reset)
+ self.assertEqual(cohort.errors_calculating, errors_calculating + (1 if expect_reset else 0))
+ mock_insert_cohort_from_query.delay.assert_not_called()
+ mock_insert_cohort_from_filters.delay.assert_not_called()
+ history = [
+ (row.error_code, row.error, row.finished_at is not None)
+ for row in CohortCalculationHistory.objects.filter(cohort=cohort).order_by("started_at")
+ ]
+ expected_history: list[tuple[CohortErrorCode | None, str | None, bool]]
+ if expect_reset:
+ interrupted = get_friendly_error_message(CohortErrorCode.INTERRUPTED, will_retry=False)
+ expected_history = [(CohortErrorCode.INTERRUPTED, interrupted, True)]
+ else:
+ expected_history = [(None, None, attempt_finished) for _, attempt_finished in attempts]
+ self.assertEqual(history, expected_history)
@parameterized.expand(
[
@@ -1848,17 +1918,7 @@ class TestCohortCalculationTasks(APIBaseTest):
name="test_filters_cohort",
is_static=True,
count=0,
- filters={
- "properties": {
- "type": "AND",
- "values": [
- {
- "type": "AND",
- "values": [{"key": "email", "type": "person", "value": "[email protected]"}],
- }
- ],
- }
- },
+ filters=PERSON_EMAIL_FILTERS,
)
with (
diff --git a/products/cohorts/backend/migrations/0016_cohort_static_calculating_idx.py b/products/cohorts/backend/migrations/0016_cohort_static_calculating_idx.py
new file mode 100644
index 000000000000..0c8ff7183321
--- /dev/null
+++ b/products/cohorts/backend/migrations/0016_cohort_static_calculating_idx.py
@@ -0,0 +1,22 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("cohorts", "0015_cohortbackfillchunk_claimable_after_and_more"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="cohort",
+ index=models.Index(
+ fields=["created_at"],
+ condition=models.Q(("deleted", False), ("is_calculating", True), ("is_static", True)),
+ name="cohort_static_calculating_idx",
+ ),
+ ),
+ ]
diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txt
index 81453f684e1b..10167e233c78 100644
--- a/products/cohorts/backend/migrations/max_migration.txt
+++ b/products/cohorts/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0015_cohortbackfillchunk_claimable_after_and_more
+0016_cohort_static_calculating_idx
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index fb7a54c01f57..00c32b8f6df1 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -333,6 +333,13 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
models.Index(fields=["team", "-created_at"], name="cohort_team_created_idx"),
# Backs `name__icontains` search (the cohort picker's server-side search).
GinIndex(fields=["name"], name="cohort_name_trgm_idx", opclasses=["gin_trgm_ops"]),
+ # Backs the stuck static cohort sweeps in posthog/tasks/calculate_cohort.py (order by created_at, limit N).
+ # Their WHERE clause must imply the condition, or the planner skips the index.
+ models.Index(
+ fields=["created_at"],
+ condition=Q(is_static=True, is_calculating=True, deleted=False),
+ name="cohort_static_calculating_idx",
+ ),
]
db_table = "posthog_cohort"
diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.py
index c477ec81b895..b16983cd986f 100644
--- a/products/cohorts/backend/models/util.py
+++ b/products/cohorts/backend/models/util.py
@@ -167,6 +167,20 @@ COHORT_STATS_COLLECTION_DELAY_SECONDS = 60 # Short delay to allow query_log to
logger = structlog.get_logger(__name__)
+def close_open_population_attempts(
+ cohort_id: int, *, finished_at: datetime, started_before: datetime | None = None
+) -> int:
+ """Records the cohort's open calculation history rows as interrupted and returns how many it closed."""
+ attempts = CohortCalculationHistory.objects.filter(cohort_id=cohort_id, finished_at__isnull=True)
+ if started_before is not None:
+ attempts = attempts.filter(started_at__lte=started_before)
+ return attempts.update(
+ finished_at=finished_at,
+ error=get_friendly_error_message(CohortErrorCode.INTERRUPTED, will_retry=False),
+ error_code=CohortErrorCode.INTERRUPTED,
+ )
+
+
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.
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index f86e6715430c..1bc23d1e4d31 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -1204,22 +1204,6 @@
'''
# ---
# name: TestFeatureFlag.test_creating_static_cohort.20
- '''
- SELECT 1 AS "a"
- FROM "posthog_cohort"
- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")
- WHERE (("posthog_cohort"."team_id" =
- (SELECT U0."parent_team_id" AS "parent_team_id"
- FROM "posthog_team" U0
- WHERE U0."id" = 99999
- LIMIT 1)
- OR ("posthog_team"."parent_team_id" IS NULL
- AND "posthog_cohort"."team_id" = 99999))
- AND "posthog_cohort"."id" = 99999)
- LIMIT 1
- '''
-# ---
-# name: TestFeatureFlag.test_creating_static_cohort.21
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1318,55 +1302,23 @@
LIMIT 21
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.22
- '''
- SELECT "posthog_filesystem"."team_id",
- "posthog_filesystem"."id",
- "posthog_filesystem"."path",
- "posthog_filesystem"."depth",
- "posthog_filesystem"."type",
- "posthog_filesystem"."ref",
- "posthog_filesystem"."href",
- "posthog_filesystem"."shortcut",
- "posthog_filesystem"."meta",
- "posthog_filesystem"."created_at",
- "posthog_filesystem"."created_by_id",
- "posthog_filesystem"."surface",
- "posthog_filesystem"."project_id"
- FROM "posthog_filesystem"
- WHERE (("posthog_filesystem"."surface" IS NULL
- OR "posthog_filesystem"."surface" = 'web')
- AND "posthog_filesystem"."ref" = '0001'
- AND "posthog_filesystem"."team_id" = 99999
- AND "posthog_filesystem"."type" = 'cohort'
- AND NOT ("posthog_filesystem"."shortcut"
- AND "posthog_filesystem"."shortcut" IS NOT NULL))
- '''
-# ---
-# name: TestFeatureFlag.test_creating_static_cohort.23
+# name: TestFeatureFlag.test_creating_static_cohort.21
'''
- SELECT "posthog_filesystemshortcut"."id",
- "posthog_filesystemshortcut"."team_id",
- "posthog_filesystemshortcut"."user_id",
- "posthog_filesystemshortcut"."path",
- "posthog_filesystemshortcut"."type",
- "posthog_filesystemshortcut"."ref",
- "posthog_filesystemshortcut"."href",
- "posthog_filesystemshortcut"."order",
- "posthog_filesystemshortcut"."created_at",
- "posthog_filesystemshortcut"."surface"
- FROM "posthog_filesystemshortcut"
- WHERE (("posthog_filesystemshortcut"."surface" IS NULL
- OR "posthog_filesystemshortcut"."surface" = 'web')
- AND "posthog_filesystemshortcut"."ref" = '0001'
- AND "posthog_filesystemshortcut"."team_id" = 99999
- AND "posthog_filesystemshortcut"."type" = 'cohort'
- AND NOT ("posthog_filesystemshortcut"."path" = 'Users with feature flag some-feature enabled at 2021-01-01 00:00:00'
- AND "posthog_filesystemshortcut"."href" = '__skipped__'
- AND "posthog_filesystemshortcut"."href" IS NOT NULL))
+ SELECT 1 AS "a"
+ FROM "posthog_cohort"
+ INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")
+ WHERE (("posthog_cohort"."team_id" =
+ (SELECT U0."parent_team_id" AS "parent_team_id"
+ FROM "posthog_team" U0
+ WHERE U0."id" = 99999
+ LIMIT 1)
+ OR ("posthog_team"."parent_team_id" IS NULL
+ AND "posthog_cohort"."team_id" = 99999))
+ AND "posthog_cohort"."id" = 99999)
+ LIMIT 1
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.24
+# name: TestFeatureFlag.test_creating_static_cohort.22
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1465,6 +1417,54 @@
LIMIT 21
'''
# ---
+# name: TestFeatureFlag.test_creating_static_cohort.23
+ '''
+ SELECT "posthog_filesystem"."team_id",
+ "posthog_filesystem"."id",
+ "posthog_filesystem"."path",
+ "posthog_filesystem"."depth",
+ "posthog_filesystem"."type",
+ "posthog_filesystem"."ref",
+ "posthog_filesystem"."href",
+ "posthog_filesystem"."shortcut",
+ "posthog_filesystem"."meta",
+ "posthog_filesystem"."created_at",
+ "posthog_filesystem"."created_by_id",
+ "posthog_filesystem"."surface",
+ "posthog_filesystem"."project_id"
+ FROM "posthog_filesystem"
+ WHERE (("posthog_filesystem"."surface" IS NULL
+ OR "posthog_filesystem"."surface" = 'web')
+ AND "posthog_filesystem"."ref" = '0001'
+ AND "posthog_filesystem"."team_id" = 99999
+ AND "posthog_filesystem"."type" = 'cohort'
+ AND NOT ("posthog_filesystem"."shortcut"
+ AND "posthog_filesystem"."shortcut" IS NOT NULL))
+ '''
+# ---
+# name: TestFeatureFlag.test_creating_static_cohort.24
+ '''
+ SELECT "posthog_filesystemshortcut"."id",
+ "posthog_filesystemshortcut"."team_id",
+ "posthog_filesystemshortcut"."user_id",
+ "posthog_filesystemshortcut"."path",
+ "posthog_filesystemshortcut"."type",
+ "posthog_filesystemshortcut"."ref",
+ "posthog_filesystemshortcut"."href",
+ "posthog_filesystemshortcut"."order",
+ "posthog_filesystemshortcut"."created_at",
+ "posthog_filesystemshortcut"."surface"
+ FROM "posthog_filesystemshortcut"
+ WHERE (("posthog_filesystemshortcut"."surface" IS NULL
+ OR "posthog_filesystemshortcut"."surface" = 'web')
+ AND "posthog_filesystemshortcut"."ref" = '0001'
+ AND "posthog_filesystemshortcut"."team_id" = 99999
+ AND "posthog_filesystemshortcut"."type" = 'cohort'
+ AND NOT ("posthog_filesystemshortcut"."path" = 'Users with feature flag some-feature enabled at 2021-01-01 00:00:00'
+ AND "posthog_filesystemshortcut"."href" = '__skipped__'
+ AND "posthog_filesystemshortcut"."href" IS NOT NULL))
+ '''
+# ---
# name: TestFeatureFlag.test_creating_static_cohort.25
'''
SELECT "posthog_cohort"."id",
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index a1ee5ad88abd..0ad2ded19463 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -8859,11 +8859,22 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
flush_persons_and_events()
cohort = self._create_static_cohort()
- mock_batch_evaluate.side_effect = [
- self._page([str(persons[0].uuid)], next_cursor=100),
- self._page([str(persons[1].uuid)], next_cursor=200),
- self._page([str(persons[2].uuid)], next_cursor=None),
- ]
+ pages = iter(
+ [
+ self._page([str(persons[0].uuid)], next_cursor=100),
+ self._page([str(persons[1].uuid)], next_cursor=200),
+ self._page([str(persons[2].uuid)], next_cursor=None),
+ ]
+ )
+ open_history_rows_during_run = []
+
+ def evaluate_page(*args, **kwargs):
+ open_history_rows_during_run.append(
+ CohortCalculationHistory.objects.filter(cohort=cohort, finished_at__isnull=True).count()
+ )
+ return next(pages)
+
+ mock_batch_evaluate.side_effect = evaluate_page
get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk, batchsize=2)
@@ -8886,6 +8897,8 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertIsNone(history.error)
self.assertEqual(history.count, 3)
self.assertIsNotNone(history.finished_at)
+ # The stuck-cohort sweep measures a live run from this open row.
+ self.assertEqual(open_history_rows_during_run, [1, 1, 1])
@patch("posthog.api.cohort.batch_evaluate_flag_for_team")
def test_history_write_failure_does_not_fail_a_populated_cohort(self, mock_batch_evaluate):
@@ -8896,7 +8909,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
mock_batch_evaluate.return_value = self._page([str(person.uuid)])
- with patch.object(CohortCalculationHistory.objects, "create", side_effect=IntegrityError("no row for you")):
+ with patch.object(CohortCalculationHistory, "save", side_effect=IntegrityError("no row for you")):
get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)
cohort.refresh_from_db()
diff --git a/products/workflows/backend/services/people_import.py b/products/workflows/backend/services/people_import.py
index 9070644725dc..138c2b514940 100644
--- a/products/workflows/backend/services/people_import.py
+++ b/products/workflows/backend/services/people_import.py
@@ -137,13 +137,15 @@ def start_people_import(*, team: Team, user: User | None, name: str, rows: list[
object_storage.write(storage_key, json.dumps(people))
capture_people_import.delay(team_id=team.id, cohort_id=cohort.pk, storage_key=storage_key)
# A worker that dies mid-task, or a task that can't schedule the next one, leaves the cohort calculating.
- # The stuck-cohort sweep skips uploaded cohorts, so this check ends the import instead.
+ # The stuck-cohort sweep resets an uploaded cohort only after SOURCELESS_STATIC_COHORT_STUCK_AFTER. The sweep
+ # does not delete the stored rows. This check ends the import sooner and deletes them.
fail_people_import_if_stalled.apply_async(
kwargs={"team_id": team.id, "cohort_id": cohort.pk, "storage_key": storage_key},
countdown=int(STALLED_IMPORT_AFTER.total_seconds()),
)
except Exception:
- # No task would finish this cohort, and the stuck-cohort sweep skips uploads.
+ # No task would finish this cohort. The stuck-cohort sweep would leave it calculating until
+ # SOURCELESS_STATIC_COHORT_STUCK_AFTER passes.
fail_people_import(team.id, cohort.pk, storage_key)
raise