: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(flags): fail flag cohort runs on per-person evaluation errors (#113692)
Phil Haackaf002282e045
diff --git a/docs/internal/feature-flags/database-interaction-patterns.md b/docs/internal/feature-flags/database-interaction-patterns.mdindex 712c49996e7c..29b83911bb15 100644--- a/docs/internal/feature-flags/database-interaction-patterns.md+++ b/docs/internal/feature-flags/database-interaction-patterns.md@@ -103,7 +103,8 @@ That includes a flag that skips DB preparation because its only group filter hasSee [Unfetched properties fail closed](flag-evaluation-engine.md#unfetched-properties-fail-closed).Each stopped call increments `flags_database_error_total` with `timeout_type="persons_db_deadline"` and the call's `operation`.The canonical log line records the first stopped call in `persons_db_deadline_exceeded`.-The internal batch evaluation endpoint does not apply the deadline. When a person's evaluation returns an error, Django leaves that person out of the static cohort and still reports the run as a success.+The internal batch evaluation endpoint does not apply the deadline.+When a person's evaluation returns an error, Django leaves that person out of the static cohort, keeps the persons that matched, and records the run as failed.The batch endpoint shares the group type mapping cache with `/flags`, so its group type lookup still stops at the 5s shared fetch cap.Set `PERSONS_DB_DEADLINE_MS=0` to disable the deadline.@@ -451,7 +452,7 @@ The batch evaluation endpoint shares these pools, so its per-person lookups getWhen a transient database fault or a timeout fails a person, the endpoint evaluates the person a second time before it counts them in `errors_count`.A `database_error` gets no second attempt, because it comes from a query that fails the same way every time.Each page allows at most 20 of these retries, so a sustained stall cannot spend the page timeout on retries.-Django leaves a person in that count out of the static cohort.+Django leaves a person in that count out of the static cohort and records the run as failed.`flags_batch_eval_person_retries_total` counts these retries by `outcome` (`recovered` or `failed`).## Related filesdiff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 19214e1fb4c9..c17bbb65ae60 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -2293,7 +2293,7 @@ BATCH_FLAG_EVALUATION_RETRY_BACKOFF_SECONDS = 2.0COHORT_FLAG_GENERATION_COMPLETED_COUNTER = Counter("cohort_flag_generation_completed_total","Cohort generations from a feature flag that finished, by outcome",- ["outcome"], # "success" or a CohortErrorCode value ("flag_changed", "unknown")+ ["outcome"], # "success" or a CohortErrorCode value)COHORT_FLAG_GENERATION_DURATION_SECONDS = Histogram(@@ -2314,6 +2314,10 @@ COHORT_FLAG_GENERATION_EVAL_ERRORS_COUNTER = Counter()+class PersonFlagEvaluationError(Exception):+ """The flags service failed to evaluate the flag for some persons. The cohort keeps the persons that matched."""++def _batch_evaluate_flag_page_with_retries(*,team_id: int,@@ -2434,62 +2438,61 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,COHORT_FLAG_GENERATION_EVAL_ERRORS_COUNTER.inc(page_errors_count)eval_errors_count += page_errors_count- if len(uuids_to_add_to_cohort) >= batchsize:+ next_cursor = page["next_cursor"]+ # save_state=False keeps the cohort calculating until this function saves the result+ # of the whole run. A caller that polls the cohort never sees a partial member list as+ # a finished one. save_state=False also re-raises an insert failure, so the except below+ # records the run as failed.+ if len(uuids_to_add_to_cohort) >= batchsize or next_cursor is None:cohort.insert_users_list_by_uuid(- uuids_to_add_to_cohort, batchsize=batchsize, team_id=team_id, raise_on_error=True+ uuids_to_add_to_cohort, batchsize=batchsize, team_id=team_id, save_state=False)uuids_to_add_to_cohort = []- next_cursor = page["next_cursor"]if next_cursor is None:breakif next_cursor <= cursor:raise RuntimeError(f"Batch flag evaluation cursor did not advance (got {next_cursor} after {cursor})")cursor = next_cursor- # Always flush, even when empty: insert_users_list_by_uuid recomputes the cohort- # count and clears is_calculating via _safe_save_cohort_state. Re-running after a- # partial failure is safe because inserts dedupe on (cohort_id, person_id).- # raise_on_error surfaces an insert failure so the except below records it rather- # than letting a partial insert be counted as a successful generation.- cohort.insert_users_list_by_uuid(- uuids_to_add_to_cohort, batchsize=batchsize, team_id=team_id, raise_on_error=True- )-+ # The cohort keeps the persons that matched. The run still fails, because a person whose+ # evaluation failed may match the flag and is missing from the cohort.if eval_errors_count:- logger.warning(- "cohort_from_feature_flag_eval_errors",- cohort_id=cohort_id,- team_id=team_id,- flag_key=feature_flag.key,- errors_count=eval_errors_count,- )+ raise PersonFlagEvaluationError(f"Flag evaluation failed for {eval_errors_count} persons")+ cohort._refresh_count(team_id=team_id)+ cohort._safe_save_cohort_state(team_id=team_id, processing_error=None)COHORT_FLAG_GENERATION_COMPLETED_COUNTER.labels(outcome="success").inc()COHORT_FLAG_GENERATION_DURATION_SECONDS.labels(outcome="success").observe(time.monotonic() - start_monotonic)- except Exception as err:+ # BaseException, so that an interruption raised into the task (SystemExit) also clears is_calculating.+ # A prefork child that receives SIGTERM or SIGKILL exits without running this handler.+ except BaseException as err:logger.exception("cohort_from_feature_flag_failed",cohort_id=cohort_id,team_id=team_id,flag_key=feature_flag.key,+ eval_errors_count=eval_errors_count,error=str(err),)capture_exception(err, additional_properties={"cohort_id": cohort_id, "team_id": team_id})- error_code = (- CohortErrorCode.FLAG_CHANGED- if isinstance(err, (FlagVersionConflictError, PropertyMatchingVersionConflictError))- else CohortErrorCode.UNKNOWN- )+ match err:+ case FlagVersionConflictError() | PropertyMatchingVersionConflictError():+ error_code = CohortErrorCode.FLAG_CHANGED+ case PersonFlagEvaluationError():+ error_code = CohortErrorCode.FLAG_EVALUATION_FAILED+ case _:+ error_code = CohortErrorCode.UNKNOWNCOHORT_FLAG_GENERATION_COMPLETED_COUNTER.labels(outcome=error_code.value).inc()COHORT_FLAG_GENERATION_DURATION_SECONDS.labels(outcome=error_code.value).observe(time.monotonic() - start_monotonic)- # Finalize cohort state before writing the history row. _safe_save_cohort_state- # swallows its own failures, so if the history insert ran first and raised, the- # cohort would stay is_calculating=True with no Celery retry to recover it+ # Finalize cohort state before writing the history row. _refresh_count and+ # _safe_save_cohort_state swallow their own failures, so if the history insert ran first+ # and raised, the cohort would stay is_calculating=True with no Celery retry to recover it# (max_retries=0). Worst case in this order is a finalized cohort missing a# history row, rather than one stuck calculating forever.+ cohort._refresh_count(team_id=team_id)cohort._safe_save_cohort_state(team_id=team_id, processing_error=err)# The history `error` field is user-visible via the calculation history API, so# store the friendly message; raw exception details (internal URLs, instance@@ -2506,7 +2509,7 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,)raise- # The flush above finalized cohort state, including the recomputed count. Recording the run+ # The save above finalized cohort state, including the recomputed count. Recording the run# here as well keeps every static population path writing one history row per attempt, so a# flag-backed cohort's calculation history is not just its failures. The write stays outside# the block above: the population is already committed, so a failure to record it must notdiff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex cc721e7bacf9..b5df513ea48e 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -516,6 +516,7 @@'_maintain_filter_shape_hashes','_meta','_person_shape_changed',+ '_refresh_count','_required_backfill_stamps','_safe_reset_calculating_state','_safe_save_cohort_state',diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex 35fd56c37e3e..a64aaf56b460 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -1016,8 +1016,10 @@ def insert_cohort_from_filters(# 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-# except block records error state and re-raises it like any other failure.+# get_cohort_actors_for_feature_flag catches BaseException, so an interruption raised into the+# task (SoftTimeLimitExceeded, SystemExit) records error state and re-raises. A prefork child+# killed by a signal runs no handler: a revoke with terminate=True, or a warm shutdown that+# outlasts the pod's termination grace period, leaves the cohort calculating.@shared_task(ignore_result=True,max_retries=0,diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex 3d0784c163e5..bcbdc040f861 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -891,6 +891,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):*,team_id: int,raise_on_error: bool = False,+ save_state: bool = True,import_resolution: ImportResolution | None = None,) -> int:"""@@ -904,6 +905,10 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):cohort state is left for the caller to finalize, instead of being swallowedand recorded on the cohort here. Use when the caller records its ownsuccess/failure outcome and must not treat a partial insert as success.+ save_state: When False, this call neither recomputes ``count`` nor saves the cohort's+ calculation state, and a batch insert failure is re-raised. The caller refreshes the+ count and saves the state. Use when the caller inserts in several calls and the+ cohort must stay calculating between them.import_resolution: Optional accumulator for deduplicated matched and unmatched UUIDs.Returns:@@ -921,6 +926,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):insert_in_clickhouse=True,team_id=team_id,raise_on_error=raise_on_error,+ save_state=save_state,insert_batch=insert_batch,)@@ -1048,6 +1054,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):*,team_id: int,raise_on_error: bool = False,+ save_state: bool = True,insert_batch: Callable[[list[Any]], None] | None = None,) -> int:"""@@ -1057,6 +1064,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):batch_iterator: BatchIterator of user UUIDs to be inserted into the cohort.insert_in_clickhouse: Whether the data should also be inserted into ClickHouse.team_id: The ID of the team to which the cohort belongs.+ raise_on_error, save_state: See ``insert_users_list_by_uuid``.insert_batch: Override for the per-batch write. Defaults to resolving each batch ofUUIDs via personhog and inserting (``_insert_batch_via_personhog``, which honors``insert_in_clickhouse``); callers whose batches are not plain UUID lists supply@@ -1065,7 +1073,6 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):Returns:Number of batches processed."""- from products.cohorts.backend.models.util import count_cohort_membersdef _resolve_and_insert_batch(batch: list[Any]) -> None:self._insert_batch_via_personhog(batch, insert_in_clickhouse, team_id=team_id)@@ -1089,10 +1096,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):raiseexcept Exception as err:processing_error = err- # When the caller owns terminal-state finalization (raise_on_error), surface- # the failure instead of swallowing it, so a partial insert can't be recorded- # as success. The finally block below skips its own error save in this mode.- if settings.DEBUG or raise_on_error:+ # When the caller owns terminal-state finalization (raise_on_error or+ # save_state=False), surface the failure instead of swallowing it, so a partial+ # insert can't be recorded as success. The finally block below skips its own+ # error save in these modes.+ if settings.DEBUG or raise_on_error or not save_state:raisecapture_exception(err,@@ -1103,28 +1111,12 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):},)finally:- # Always update the count and cohort state, even if processing failed- try:- count = count_cohort_members(cohort_id=self.id, team_id=self.team_id, consistency="strong")- self.count = count- except Exception as count_err:- # If count calculation fails, log the error but don't override the processing error.- # Leave existing count unchanged - it's better than None.- logger.exception(- "Failed to calculate static cohort size",- cohort_id=self.id,- team_id=team_id,- )- capture_exception(- count_err,- additional_properties={"cohort_id": self.id, "team_id": team_id},- )-- # In raise_on_error mode the caller finalizes cohort state on failure, so skip- # the error save here to avoid double-counting errors_calculating. The success- # path (processing_error is None) still finalizes state as usual.- if not (raise_on_error and processing_error is not None):- self._safe_save_cohort_state(team_id=team_id, processing_error=processing_error)+ if save_state:+ self._refresh_count(team_id=team_id)+ # In raise_on_error mode the caller finalizes cohort state on failure, so skip+ # the error save here to avoid double-counting errors_calculating.+ if processing_error is None or not raise_on_error:+ self._safe_save_cohort_state(team_id=team_id, processing_error=processing_error)return current_batch_index + 1@@ -1320,6 +1312,24 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):}return {k: v for k, v in base_dict.items() if k not in excluded_fields}+ def _refresh_count(self, *, team_id: int) -> None:+ """Recompute ``count`` on the instance from the stored members. A failure is logged, not raised."""+ from products.cohorts.backend.models.util import count_cohort_members++ try:+ self.count = count_cohort_members(cohort_id=self.id, team_id=self.team_id, consistency="strong")+ except Exception as count_err:+ # A failed count leaves the existing count unchanged. An old count is better than None.+ logger.exception(+ "Failed to calculate static cohort size",+ cohort_id=self.id,+ team_id=team_id,+ )+ capture_exception(+ count_err,+ additional_properties={"cohort_id": self.id, "team_id": team_id},+ )+def _safe_save_cohort_state(self, *, team_id: int, processing_error=None) -> None:"""Save only the cohort's calculation-state fields with a single retry on failure.diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.pyindex eda2dd5be441..5c764734d0b6 100644--- a/products/cohorts/backend/models/test/test_util.py+++ b/products/cohorts/backend/models/test/test_util.py@@ -1296,6 +1296,7 @@ class TestGetFriendlyErrorMessage(BaseTest):(CohortErrorCode.INVALID_REGEX, "invalid regular expression"),(CohortErrorCode.INCOMPATIBLE_TYPES, "an error occurred"),(CohortErrorCode.NO_PROPERTIES, "no matching criteria"),+ (CohortErrorCode.FLAG_EVALUATION_FAILED, "couldn't evaluate the feature flag"),(CohortErrorCode.UNKNOWN, "an error occurred"),])diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex 5ee5edd0fc7a..c477ec81b895 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -82,6 +82,7 @@ class CohortErrorCode(StrEnum):INCOMPATIBLE_TYPES = "incompatible_types"NO_PROPERTIES = "no_properties"FLAG_CHANGED = "flag_changed"+ FLAG_EVALUATION_FAILED = "flag_evaluation_failed"UNKNOWN = "unknown"@@ -101,6 +102,7 @@ ERROR_CODE_MESSAGES: dict[str, str] = {CohortErrorCode.VALIDATION_ERROR: UNEXPECTED_ERROR_MESSAGE,CohortErrorCode.INCOMPATIBLE_TYPES: UNEXPECTED_ERROR_MESSAGE,CohortErrorCode.FLAG_CHANGED: "The feature flag changed while this cohort was being calculated. Please run the calculation again.",+ CohortErrorCode.FLAG_EVALUATION_FAILED: "We couldn't evaluate the feature flag for some people, so this cohort may be missing people who match it. Create a new cohort from the flag to try again.",CohortErrorCode.UNKNOWN: UNEXPECTED_ERROR_MESSAGE,}diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 621dd2edcfc4..652ba8a2d4b8 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -22,6 +22,7 @@ from django.utils.timezone import nowimport grpcimport requests+from celery.exceptions import SoftTimeLimitExceededfrom parameterized import parameterizedfrom prometheus_client import REGISTRYfrom rest_framework import status@@ -31,7 +32,11 @@ from rest_framework.response import Responsefrom posthog.hogql.database.database import Databasefrom posthog import redis-from posthog.api.cohort import BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS, get_cohort_actors_for_feature_flag+from posthog.api.cohort import (+ BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS,+ PersonFlagEvaluationError,+ get_cohort_actors_for_feature_flag,+)from posthog.api.services.flags_service import FlagVersionConflictError, PropertyMatchingVersionConflictErrorfrom posthog.api.utils import ServiceRequestfrom posthog.constants import AvailableFeature@@ -9507,8 +9512,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):self._create_flag()cohort = self._create_static_cohort()- # The final flush is unconditional precisely so a zero-match run still recomputes- # count to 0 and clears is_calculating, instead of leaving the cohort stuck.+ # A zero-match run inserts nobody and still records a count of 0 instead of leaving it unset.mock_batch_evaluate.return_value = self._page([])get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)@@ -9594,6 +9598,29 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(history.error_code, CohortErrorCode.UNKNOWN)self.assertEqual(history.error, get_friendly_error_message(CohortErrorCode.UNKNOWN))+ @parameterized.expand(+ [+ ("soft_time_limit", SoftTimeLimitExceeded()),+ # SystemExit is not an Exception, so this case fails if the orchestrator catches only Exception.+ ("worker_shutdown", SystemExit()),+ ]+ )+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")+ def test_interrupted_run_is_recorded_as_failure(self, _name, interruption, mock_batch_evaluate):+ self._create_flag()+ cohort = self._create_static_cohort()+ cohort.is_calculating = True+ cohort.save(update_fields=["is_calculating"])++ mock_batch_evaluate.side_effect = interruption++ with self.assertRaises(type(interruption)):+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ cohort.refresh_from_db()+ self.assertEqual((cohort.is_calculating, cohort.errors_calculating), (False, 1))+ self.assertEqual(CohortCalculationHistory.objects.get(cohort=cohort).error_code, CohortErrorCode.UNKNOWN)+@patch("posthog.api.cohort.time.sleep")@patch("posthog.api.cohort.batch_evaluate_flag_for_team")def test_transient_errors_retry_then_succeed(self, mock_batch_evaluate, mock_sleep):@@ -9744,19 +9771,38 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(len(response.json()["results"]), 1, response)@patch("posthog.api.cohort.batch_evaluate_flag_for_team")- def test_per_person_eval_errors_do_not_fail_the_run(self, mock_batch_evaluate):+ def test_per_person_eval_errors_fail_the_run_and_keep_matched_persons(self, mock_batch_evaluate):self._create_flag()- person = _create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"}, immediate=True)+ persons = [+ _create_person(team=self.team, distinct_ids=[f"person{i}"], properties={"key": "value"}, immediate=True)+ for i in range(2)+ ]flush_persons_and_events()cohort = self._create_static_cohort()- mock_batch_evaluate.return_value = self._page([str(person.uuid)], errors_count=5)+ # The errors are on the first page, so this test fails if the run checks only the last page's count.+ mock_batch_evaluate.side_effect = [+ self._page([str(persons[0].uuid)], next_cursor=50, errors_count=5),+ self._page([str(persons[1].uuid)], next_cursor=None),+ ]- get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)+ success_before = self._metric("cohort_flag_generation_completed_total", outcome="success")+ failed_before = self._metric("cohort_flag_generation_completed_total", outcome="flag_evaluation_failed")++ with self.assertRaises(PersonFlagEvaluationError):+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)++ self.assertEqual(self._metric("cohort_flag_generation_completed_total", outcome="success"), success_before)+ self.assertEqual(+ self._metric("cohort_flag_generation_completed_total", outcome="flag_evaluation_failed"),+ failed_before + 1,+ )cohort.refresh_from_db()- self.assertEqual(cohort.count, 1)- self.assertEqual(cohort.errors_calculating, 0)+ self.assertEqual((cohort.count, cohort.is_calculating, cohort.errors_calculating), (2, False, 1))+ history = CohortCalculationHistory.objects.get(cohort=cohort)+ self.assertEqual(history.error_code, CohortErrorCode.FLAG_EVALUATION_FAILED)+ self.assertEqual(history.error, get_friendly_error_message(history.error_code, will_retry=False))@patch("posthog.api.cohort.batch_evaluate_flag_for_team")def test_insert_batching_flushes_mid_run(self, mock_batch_evaluate):@@ -9769,28 +9815,38 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):]flush_persons_and_events()cohort = self._create_static_cohort()+ cohort.is_calculating = True+ cohort.save(update_fields=["is_calculating"])mock_batch_evaluate.side_effect = [self._page([str(persons[0].uuid), str(persons[1].uuid)], next_cursor=50),self._page([str(persons[2].uuid)], next_cursor=None),]- with patch.object(- Cohort, "insert_users_list_by_uuid", autospec=True, side_effect=Cohort.insert_users_list_by_uuid- ) as mock_insert:+ # A cohort that reads as finished before the run ends lets a caller act on a partial+ # member list, so no flush may clear is_calculating.+ insert = Cohort.insert_users_list_by_uuid+ is_calculating_after_each_flush: list[bool] = []++ def insert_then_read_state(self_: Cohort, *args: Any, **kwargs: Any) -> int:+ batches = insert(self_, *args, **kwargs)+ is_calculating_after_each_flush.append(Cohort.objects.get(pk=cohort.pk).is_calculating)+ return batches++ with patch.object(Cohort, "insert_users_list_by_uuid", autospec=True, side_effect=insert_then_read_state):get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk, batchsize=2)# One mid-run flush (buffer hit batchsize) + the final flush- self.assertEqual(mock_insert.call_count, 2)+ self.assertEqual(is_calculating_after_each_flush, [True, True])cohort.refresh_from_db()- self.assertEqual(cohort.count, 3)+ self.assertEqual((cohort.count, cohort.is_calculating), (3, False))@patch("posthog.api.cohort.batch_evaluate_flag_for_team")def test_insert_failure_is_recorded_as_failure_not_success(self, mock_batch_evaluate):# A DB/ClickHouse failure while inserting matched persons must surface as a failed- # generation (the insert runs with raise_on_error=True), not be swallowed and+ # generation (the insert runs with save_state=False, which re-raises), not be swallowed and# counted as success. DEBUG is forced off so the production swallow path is what- # would run without raise_on_error.+ # would run without save_state=False.self._create_flag()person = _create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"}, immediate=True)flush_persons_and_events()