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): surface a static cohort's failed population (#101285)

Phil Haack6c2b1d5056d2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index bf97e883b857..ca8a50b4ccba 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9393,9 +9393,13 @@ snapshots:
scenes-app-people-cohorts--cohort-edit-dynamic--light:
hash: v1.k794b7964.16bae00697363fb140788023823ca272a1f57bf2b9cc4984f62f6b39e098b87a.sga7qTbJWVb7MG-E8DSdsDVlcJm9nBZzZAY6TxrBIUw
scenes-app-people-cohorts--cohort-edit-static--dark:
- hash: v1.k794b7964.9a7ecdb86d86a13d5ea9c1723b11d6ee9e712851ce610a1f22087f17e4a13c2e.PFmgqeNOFUte6e2WGILBNqWzV9SGyXqGATqt9qX8UcQ
+ hash: v1.k794b7964.267b40e33b380519b46d4b7b8068b869a6250b5fd446c6335a9e95f683ee2302.jnRu9rG_ZQxTsYzmKQqEbN-aIU3psCpbQN8hV8OsX6Y
scenes-app-people-cohorts--cohort-edit-static--light:
- hash: v1.k794b7964.26110785e678568b3be042baeba86b30387e473843b8a65aa48b11edfdd24af7.5Z104Qke5HLoSoHtuKjQoVVoTGvswRtlNGWgu5Y6lL8
+ hash: v1.k794b7964.ccca565eab13d0a15b96b664f72fe2a86cd7f94f71144041020507f80e4f0123.7Aj84hi9A22Kzcp0q7Whjal9N_XI9QOHNqHjB2DFRgs
+ scenes-app-people-cohorts--cohort-edit-static-population-failed--dark:
+ hash: v1.k794b7964.56f875299f9005db364cc362050e4d425528d2205c202def0d2a6e98c9745b25.tXvxMJzkKQb5UhOTQMrfwndgLUz8aBUxAaSvpdQtl2I
+ scenes-app-people-cohorts--cohort-edit-static-population-failed--light:
+ hash: v1.k794b7964.3c2fb12b8b97a3126412bd6667a2873d37f97288b86d90afed2ff6ff12f320f3.RLtxz6gSL0p-CpgRQE5RdOzgVgAkyPBRz4yMz8IgbDM
scenes-app-people-cohorts--cohort-new--dark:
hash: v1.k794b7964.0c0b9da85f85dac4c299d0527725f192c0c07d204e28462a64736552aaba735b.aX2s9DQu-pQIZHJDYBeZXL9lyni7w6PSMh3u3b_cvhA
scenes-app-people-cohorts--cohort-new--light:
diff --git a/frontend/src/scenes/cohorts/CohortEdit.test.tsx b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
index 0b753ca00753..08b59e9ac2f4 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.test.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.test.tsx
@@ -9,6 +9,7 @@ import { NEW_COHORT } from 'scenes/cohorts/CohortFilters/constants'
import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
import { urls } from 'scenes/urls'
+import { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'
import { toPaginatedResponse } from '~/mocks/handlers'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -423,6 +424,38 @@ describe('cohortEditLogic', () => {
expect(screen.queryByText(/Calculation failed:/)).not.toBeInTheDocument()
})
+ it('shows the failure banner without a retry for a static cohort whose population failed', async () => {
+ const cohortId = 7
+
+ useMocks({
+ get: {
+ [`/api/projects/:team_id/cohorts/${cohortId}/`]: {
+ id: cohortId,
+ name: 'Test Cohort',
+ // A static cohort that never populated reports count 0, so the only signal
+ // that the population failed is this banner.
+ is_static: true,
+ filters: { properties: {} },
+ query: { kind: 'HogQLQuery', query: 'SELECT person_id FROM events' },
+ version: null,
+ pending_version: null,
+ is_calculating: false,
+ errors_calculating: 1,
+ last_calculation: null,
+ last_error_message: 'Cohort calculation was terminated for reading too much data.',
+ },
+ },
+ })
+
+ render(<CohortEdit id={cohortId} />)
+
+ await screen.findByText(/Calculation failed:/)
+ expect(screen.getByText(/reading too much data/)).toBeInTheDocument()
+ expect(screen.getByText('contact support')).toBeInTheDocument()
+ // The edit form does not resend the source query, so a Retry would not repopulate.
+ expect(screen.queryByText('Retry')).not.toBeInTheDocument()
+ })
+
// Pins the selector contract the fix changed, including the errors_calculating=0 and
// version=null boundaries the DOM tests above don't exercise.
it.each([
@@ -494,6 +527,61 @@ describe('cohortEditLogic', () => {
)
})
+ describe('calculation history action', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ // ScenePanel portals its actions into the host element the app layout registers. A
+ // standalone render never creates one, so the panel stays empty without this.
+ function renderWithScenePanel(cohortId: number): void {
+ const panelHost = document.createElement('div')
+ document.body.appendChild(panelHost)
+ const layoutLogic = sceneLayoutLogic()
+ layoutLogic.mount()
+ layoutLogic.actions.registerScenePanelElement(panelHost)
+ render(<CohortEdit id={cohortId} />)
+ }
+
+ it.each([
+ { type: 'static', isStatic: true },
+ { type: 'dynamic', isStatic: false },
+ ])('offers calculation history for a saved $type cohort', async ({ isStatic }) => {
+ const cohortId = 8
+
+ useMocks({
+ get: {
+ [`/api/projects/:team_id/cohorts/${cohortId}/`]: {
+ id: cohortId,
+ name: 'Test Cohort',
+ is_static: isStatic,
+ filters: { properties: { type: 'AND', values: [] } },
+ version: null,
+ pending_version: null,
+ is_calculating: false,
+ errors_calculating: 0,
+ last_calculation: null,
+ },
+ },
+ })
+
+ renderWithScenePanel(cohortId)
+
+ // The panel fills in behind a one second timer, so the default one second find budget
+ // has almost no margin. Waiting on a sibling action also separates a panel that never
+ // rendered from one that rendered without this entry.
+ await screen.findByText('Message this cohort', {}, { timeout: 5000 })
+
+ // An unloaded cohort has a falsy is_static, which satisfies the gate this test exists
+ // to catch, so pin that the fixture reached the scene before asserting on it.
+ expect(screen.getByText(isStatic ? 'Static' : 'Dynamic')).toBeInTheDocument()
+
+ // Both cohort types record calculation history, so neither may have the tab that lists
+ // it gated away.
+ expect(screen.getByText('Calculation history')).toBeInTheDocument()
+ })
+ })
+
describe('import warning', () => {
afterEach(() => {
cleanup()
diff --git a/frontend/src/scenes/cohorts/CohortEdit.tsx b/frontend/src/scenes/cohorts/CohortEdit.tsx
index 2dbe56be868e..4fdbe775045b 100644
--- a/frontend/src/scenes/cohorts/CohortEdit.tsx
+++ b/frontend/src/scenes/cohorts/CohortEdit.tsx
@@ -333,17 +333,15 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
</ButtonPrimitive>
)}
- {!cohort.is_static && (
- <ButtonPrimitive
- onClick={() => router.actions.push(urls.cohortCalculationHistory(cohort.id))}
- disabledReasons={{
- 'Save the cohort first': isNewCohort,
- }}
- menuItem
- >
- <IconClock /> Calculation history
- </ButtonPrimitive>
- )}
+ <ButtonPrimitive
+ onClick={() => router.actions.push(urls.cohortCalculationHistory(cohort.id))}
+ disabledReasons={{
+ 'Save the cohort first': isNewCohort,
+ }}
+ menuItem
+ >
+ <IconClock /> Calculation history
+ </ButtonPrimitive>
</ScenePanelActionsSection>
{!isNewCohort && (
<>
@@ -541,21 +539,23 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
</div>
)}
- {!isNewCohort && !cohort?.is_static && (
+ {!isNewCohort && (
<div className="flex flex-col gap-y-2">
- <div className="flex items-center gap-x-2 my-0">
- <strong>Last calculated:</strong>
- {isCalculatingOrPending ? (
- <div className="flex items-center gap-x-2">
- <Spinner size="small" />
- <span className="text-muted">In progress...</span>
- </div>
- ) : cohort.last_calculation ? (
- <TZLabel time={cohort.last_calculation} />
- ) : (
- <span className="text-muted">Not yet calculated</span>
- )}
- </div>
+ {!cohort.is_static && (
+ <div className="flex items-center gap-x-2 my-0">
+ <strong>Last calculated:</strong>
+ {isCalculatingOrPending ? (
+ <div className="flex items-center gap-x-2">
+ <Spinner size="small" />
+ <span className="text-muted">In progress...</span>
+ </div>
+ ) : cohort.last_calculation ? (
+ <TZLabel time={cohort.last_calculation} />
+ ) : (
+ <span className="text-muted">Not yet calculated</span>
+ )}
+ </div>
+ )}
{isCalculatingOrPending ? (
<LemonBanner type="warning">
@@ -570,15 +570,26 @@ export function CohortEdit({ id, attachTo }: CohortEditProps): JSX.Element {
) : cohort.errors_calculating ? (
<LemonBanner
type="error"
- action={{
- onClick: () => submitCohort(),
- children: 'Retry',
- }}
+ // A static cohort is populated once from the source it was created
+ // with, and the edit form does not resend that source, so saving the
+ // cohort again would not run the population.
+ action={
+ cohort.is_static
+ ? undefined
+ : {
+ onClick: () => submitCohort(),
+ children: 'Retry',
+ }
+ }
>
<strong>Calculation failed:</strong>{' '}
{cohort.last_error_message ||
- 'Unable to calculate this cohort. Please check your matching criteria and try again.'}{' '}
- If it fails again,{' '}
+ (cohort.is_static
+ ? 'Unable to populate this cohort from its source.'
+ : 'Unable to calculate this cohort. Please check your matching criteria and try again.')}{' '}
+ {cohort.is_static
+ ? 'If it keeps happening, '
+ : 'If it fails again, '}
<Link
onClick={() =>
openSidePanel(SidePanelTab.Support, 'bug:cohorts::true')
diff --git a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx
index 4da48a966f06..91b121a50642 100644
--- a/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx
+++ b/frontend/src/scenes/cohorts/CohortSceneMenuBar.tsx
@@ -84,7 +84,7 @@ function CohortSceneMenuBarInner({ id }: { id?: CohortType['id'] }): JSX.Element
Copy to another project
</SceneMenuBarItem>
)}
- {!isNewCohort && !cohort.is_static && (
+ {!isNewCohort && (
<SceneMenuBarItem
onClick={() => router.actions.push(urls.cohortCalculationHistory(cohort.id))}
data-attr={`${RESOURCE_TYPE}-menubar-calculation-history`}
diff --git a/frontend/src/scenes/cohorts/Cohorts.stories.tsx b/frontend/src/scenes/cohorts/Cohorts.stories.tsx
index ed934d50a5a8..5e315003504f 100644
--- a/frontend/src/scenes/cohorts/Cohorts.stories.tsx
+++ b/frontend/src/scenes/cohorts/Cohorts.stories.tsx
@@ -77,3 +77,14 @@ export const CohortEditStatic: Story = {
parameters: { pageUrl: urls.cohort(3) },
decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/3/': mockCohorts[2], ...cohortApiMocks } })],
}
+
+const failedStaticCohort: CohortType = {
+ ...createCohort(4, 'Beta signups snapshot', 0, true),
+ errors_calculating: 1,
+ last_error_message: 'Cohort calculation was terminated for reading too much data.',
+} as CohortType
+
+export const CohortEditStaticPopulationFailed: Story = {
+ parameters: { pageUrl: urls.cohort(4) },
+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/cohorts/4/': failedStaticCohort, ...cohortApiMocks } })],
+}
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
index 66f7e64bfffa..6bc84356750f 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.test.ts
@@ -172,21 +172,28 @@ describe('cohortEditLogic', () => {
})
describe('calculation polling', () => {
- it('refreshes import counts when calculation finishes', async () => {
+ // The final poll response is the only thing that refreshes these fields while the page
+ // stays open, so a field the merge drops keeps its stale value until a reload.
+ it.each([
+ ['import counts', { last_import_total_count: 5, last_import_unmatched_count: 3 }],
+ [
+ 'failure reason',
+ {
+ errors_calculating: 1,
+ last_error_message: 'Cohort calculation was terminated for reading too much data.',
+ },
+ ],
+ ])('refreshes %s when calculation finishes', async (_, finishedFields) => {
await initCohortLogic({ id: 1 })
await expectLogic(logic, () => {
logic.actions.checkIfFinishedCalculating({
...mockCohort,
is_calculating: false,
- last_import_total_count: 5,
- last_import_unmatched_count: 3,
+ ...finishedFields,
})
}).toMatchValues({
- cohort: partial({
- last_import_total_count: 5,
- last_import_unmatched_count: 3,
- }),
+ cohort: partial(finishedFields),
})
})
})
diff --git a/frontend/src/scenes/cohorts/cohortEditLogic.ts b/frontend/src/scenes/cohorts/cohortEditLogic.ts
index 2af0d8e5ed20..5e2350ae37e6 100644
--- a/frontend/src/scenes/cohorts/cohortEditLogic.ts
+++ b/frontend/src/scenes/cohorts/cohortEditLogic.ts
@@ -1160,6 +1160,7 @@ export const cohortEditLogic = kea<cohortEditLogicType>([
const calculationFields = {
is_calculating: cohort.is_calculating,
errors_calculating: cohort.errors_calculating,
+ last_error_message: cohort.last_error_message,
last_calculation: cohort.last_calculation,
count: cohort.count,
last_import_total_count: cohort.last_import_total_count,
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index dad3b695c122..6d3c42029f12 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -761,10 +761,14 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
self.fields.pop(field_name, None)
def get_last_error_message(self, cohort: Cohort) -> Optional[str]:
+ # A static cohort is populated once, and nothing re-runs it afterwards, so the messages
+ # that promise an automatic retry must not reach one.
+ will_retry = not cohort.is_static
+
# Prefer the annotated last_error_code when available
if hasattr(cohort, "last_error_code"):
if cohort.last_error_code:
- return get_friendly_error_message(cohort.last_error_code)
+ return get_friendly_error_message(cohort.last_error_code, will_retry=will_retry)
return None
# Fall back to querying calculation history.
@@ -778,7 +782,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializ
.first()
)
if last_failed_calculation:
- return get_friendly_error_message(last_failed_calculation.error_code)
+ return get_friendly_error_message(last_failed_calculation.error_code, will_retry=will_retry)
return None
def validate_cohort_type(self, value):
@@ -2368,14 +2372,39 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,
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
- # config) stay in logs and error tracking only.
+ # 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),
+ error=get_friendly_error_message(error_code, will_retry=False),
error_code=error_code,
)
raise
+
+ # The flush 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 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,
+ )
+ except Exception as err:
+ logger.warning(
+ "cohort_from_feature_flag_history_write_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})
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 982c4bc0454d..efe721619a55 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -5804,6 +5804,44 @@ [email protected],
self.assertIsNotNone(response.json()["last_error_message"])
self.assertIn("taking too long", response.json()["last_error_message"].lower())
+ @parameterized.expand(
+ [
+ ("dynamic", False, True),
+ ("static", True, False),
+ ]
+ )
+ def test_cohort_last_error_message_promises_a_retry_only_when_one_will_run(
+ self, _name: str, is_static: bool, promises_retry: bool
+ ):
+ from products.cohorts.backend.models.calculation_history import CohortCalculationHistory
+ from products.cohorts.backend.models.util import CohortErrorCode
+
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="Test Cohort",
+ is_static=is_static,
+ errors_calculating=1,
+ )
+
+ CohortCalculationHistory.objects.create(
+ cohort=cohort,
+ team=self.team,
+ filters={},
+ started_at=timezone.now(),
+ finished_at=timezone.now(),
+ error="The system was busy when this cohort was scheduled to calculate.",
+ error_code=CohortErrorCode.CAPACITY,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort.id}")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ message = response.json()["last_error_message"].lower()
+ self.assertIn("system was busy", message)
+ # The periodic queue excludes static cohorts and the stuck sweeper only matches one still
+ # calculating, so a static cohort must not be told to wait for a retry that never comes.
+ self.assertEqual("automatically retry" in message, promises_retry)
+
def test_cohort_last_error_message_in_list_view(self):
"""Test that list view includes last_error_message via annotation"""
from products.cohorts.backend.models.calculation_history import CohortCalculationHistory
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index 66f48de7898c..35fd56c37e3e 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -44,9 +44,12 @@ from products.cohorts.backend.models.calculation_history import CohortCalculatio
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, ImportResolution
from products.cohorts.backend.models.util import (
COHORT_STATS_COLLECTION_DELAY_SECONDS,
+ CohortErrorCode,
get_all_cohort_dependencies,
get_all_cohort_dependents,
get_clickhouse_query_stats,
+ get_friendly_error_message,
+ parse_error_code,
save_recovery_bookkeeping,
sort_cohorts_topologically,
)
@@ -713,6 +716,7 @@ def calculate_cohort_from_list(
raise ValueError(f"Unsupported id_type: {id_type}")
cohort: Cohort | None = None
+ history: CohortCalculationHistory | 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.
@@ -724,6 +728,16 @@ def calculate_cohort_from_list(
if _static_population_obsolete(self, cohort):
return
+ # An import that fails without a row of its own resolves `last_error_message` to whichever
+ # older population failed, because that lookup takes the newest errored row over the
+ # cohort's whole life. Recording the attempt also keeps imports in the calculation history
+ # beside the query and filter population paths.
+ history = CohortCalculationHistory.objects.create(
+ team_id=cohort.team_id,
+ cohort=cohort,
+ filters=cohort.properties.to_dict() if cohort.properties.values else {},
+ )
+
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
@@ -763,6 +777,12 @@ def calculate_cohort_from_list(
processing_error = err
raise
finally:
+ # One history row records one attempt, so every exit closes it, including a scheduled
+ # retry. An open row left behind would read as an import still in flight.
+ if history is not None and cohort is not None:
+ _finalize_population_history(
+ history, cohort=cohort, processing_error=processing_error, will_retry=retry is not None
+ )
# 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.
@@ -775,6 +795,41 @@ def calculate_cohort_from_list(
)
+def _finalize_population_history(
+ history: CohortCalculationHistory,
+ *,
+ cohort: Cohort,
+ processing_error: BaseException | None,
+ will_retry: bool,
+) -> None:
+ """Close out the history record for one static population attempt.
+
+ `will_retry` says whether this attempt scheduled another one. The history tab renders each
+ row's message verbatim, so an attempt with a retry queued keeps the copy that says so.
+ """
+ history.finished_at = timezone.now()
+ if processing_error is None:
+ history.count = cohort.count
+ else:
+ # parse_error_code classifies exceptions. A BaseException that stopped the worker
+ # (shutdown, revoke) carries no cause worth showing, so it stays unknown.
+ history.error_code = (
+ parse_error_code(processing_error) if isinstance(processing_error, Exception) else CohortErrorCode.UNKNOWN
+ )
+ # The calculation history API serves `error` to anyone with cohort read access, and the
+ # history tab renders it verbatim. Raw exception text names the responding ClickHouse host
+ # and quotes the failing SQL, so only the friendly message is stored; the exception itself
+ # stays in the logs and in error tracking.
+ history.error = get_friendly_error_message(history.error_code, will_retry=will_retry)
+ # A long population can outlive its Postgres connection, so record the outcome resiliently
+ # instead of raising "connection is closed" over the error this row exists to report.
+ save_recovery_bookkeeping(
+ lambda: history.save(update_fields=["finished_at", "count", "error", "error_code"]),
+ cohort_id=cohort.pk,
+ team_id=cohort.team_id,
+ )
+
+
def _populate_static_cohort(
task: Task,
*,
@@ -794,6 +849,7 @@ def _populate_static_cohort(
# 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
+ history: CohortCalculationHistory | None = None
processing_error: BaseException | None = None
retry: Retry | None = None
try:
@@ -819,6 +875,14 @@ def _populate_static_cohort(
claimed = cohort
cohort.refresh_from_db()
+ # A history record is the only way a population failure reaches the user: the cohort API
+ # reads `last_error_message` from the newest history row that carries an error. Without one,
+ # a population that died on a ClickHouse limit is indistinguishable from a cohort that
+ # matched nobody.
+ history = CohortCalculationHistory.objects.create(
+ team=team, cohort=cohort, filters=cohort.properties.to_dict() if cohort.properties.values else {}
+ )
+
# 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). A retry whose earlier attempt
@@ -861,6 +925,12 @@ def _populate_static_cohort(
processing_error = err
raise
finally:
+ # One history row records one attempt, so every exit closes it, including a scheduled
+ # retry. An open row left behind would read as a population still in flight.
+ if history is not None and claimed is not None:
+ _finalize_population_history(
+ history, cohort=claimed, processing_error=processing_error, will_retry=retry is not None
+ )
# 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.
diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.py
index 48920c222021..01f471103cb0 100644
--- a/posthog/tasks/test/test_calculate_cohort.py
+++ b/posthog/tasks/test/test_calculate_cohort.py
@@ -45,8 +45,15 @@ from posthog.test.persons import create_person
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.calculation_history import CohortCalculationHistory
from products.cohorts.backend.models.cohort import Cohort, CohortType
-from products.cohorts.backend.models.util import count_cohort_members, insert_static_cohort, list_cohort_member_ids
+from products.cohorts.backend.models.util import (
+ CohortErrorCode,
+ count_cohort_members,
+ get_friendly_error_message,
+ insert_static_cohort,
+ list_cohort_member_ids,
+)
MISSING_COHORT_ID = 12345
@@ -1515,6 +1522,17 @@ class TestCohortCalculationTasks(APIBaseTest):
self.assertFalse(cohort.is_calculating)
self.assertIsNone(cohort.last_calculation)
+ # The history row is what the cohort API reads `last_error_message` from, so without it the
+ # failed population reads as a cohort that matched nobody.
+ history = CohortCalculationHistory.objects.get(cohort=cohort)
+ self.assertEqual(history.error_code, CohortErrorCode.UNKNOWN)
+ self.assertIsNotNone(history.finished_at)
+ # The history tab renders `error` verbatim to anyone with cohort read access, so the raw
+ # exception text stays out of it.
+ self.assertEqual(history.error, get_friendly_error_message(CohortErrorCode.UNKNOWN, will_retry=False))
+ assert history.error is not None
+ self.assertNotIn("personhog unavailable", history.error)
+
@parameterized.expand(
[
(
@@ -1596,6 +1614,73 @@ class TestCohortCalculationTasks(APIBaseTest):
self.assertIsNone(cohort.last_calculation)
self.assertIsNotNone(cohort.last_error_at)
+ @parameterized.expand(
+ [
+ ("retry_scheduled", 0, True),
+ ("retries_exhausted", STATIC_POPULATION_MAX_RETRIES, False),
+ ]
+ )
+ @override_settings(DEBUG=False)
+ def test_static_population_history_records_whether_another_attempt_is_coming(
+ self, _name: str, retries: int, another_attempt_coming: bool
+ ) -> None:
+ cohort = Cohort.objects.create(team=self.team, name="static cohort", is_static=True, is_calculating=True)
+ insert_cohort_from_query.push_request(retries=retries, called_directly=False, is_eager=True)
+ try:
+ with patch(QUERY_CH_INSERT_PATH), patch(PG_SYNC_PATH, side_effect=ClickHouseAtCapacity()):
+ if another_attempt_coming:
+ with self.assertRaises(Retry):
+ insert_cohort_from_query.run(cohort.id, self.team.pk)
+ else:
+ insert_cohort_from_query.run(cohort.id, self.team.pk)
+ finally:
+ insert_cohort_from_query.pop_request()
+
+ # One row records one attempt, so a queued retry must not leave this one open and reading
+ # as a population still in flight.
+ history = CohortCalculationHistory.objects.get(cohort=cohort)
+ self.assertIsNotNone(history.finished_at)
+ self.assertEqual(history.error_code, CohortErrorCode.CAPACITY)
+ assert history.error is not None
+ # The history tab renders this text per attempt, so an attempt that already queued another
+ # one must not read as terminal.
+ self.assertEqual("automatically retry" in history.error, another_attempt_coming)
+
+ def test_a_failed_import_records_its_own_reason_rather_than_an_older_one(self) -> None:
+ cohort = Cohort.objects.create(team=self.team, name="static cohort", is_static=True)
+ person = create_person(team=self.team, distinct_ids=["import-failure"])
+ # An earlier query population failed and left the newest errored row. `last_error_message`
+ # takes that row over the cohort's whole life, so an import that records nothing of its own
+ # reports this stale reason in place of the one that just happened.
+ CohortCalculationHistory.objects.create(
+ team=self.team,
+ cohort=cohort,
+ filters={},
+ started_at=timezone.now() - relativedelta(hours=1),
+ finished_at=timezone.now() - relativedelta(hours=1),
+ error=get_friendly_error_message(CohortErrorCode.DATA_LIMIT, will_retry=False),
+ error_code=CohortErrorCode.DATA_LIMIT,
+ )
+
+ with (
+ patch(
+ "products.cohorts.backend.models.util.insert_cohort_members",
+ side_effect=ValueError("personhog unavailable"),
+ ),
+ self.assertRaises(ValueError),
+ ):
+ calculate_cohort_from_list(cohort.id, [str(person.uuid)], team_id=self.team.pk, id_type="person_id")
+
+ newest_failure = (
+ CohortCalculationHistory.objects.filter(cohort=cohort)
+ .exclude(error__isnull=True)
+ .order_by("-started_at")
+ .first()
+ )
+ assert newest_failure is not None
+ self.assertEqual(newest_failure.error_code, CohortErrorCode.UNKNOWN)
+ self.assertIsNotNone(newest_failure.finished_at)
+
@parameterized.expand(
[
("query", insert_cohort_from_query, QUERY_CH_INSERT_PATH),
diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.py
index 2727ef1abf02..eda2dd5be441 100644
--- a/products/cohorts/backend/models/test/test_util.py
+++ b/products/cohorts/backend/models/test/test_util.py
@@ -28,6 +28,7 @@ from posthog.models.person.sql import PERSON_STATIC_COHORT_TABLE
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
from products.cohorts.backend.models.util import (
+ ERROR_CODE_MESSAGES,
CohortErrorCode,
_recalculate_cohortpeople_for_team,
_sanitize_query_for_cohort,
@@ -1226,6 +1227,7 @@ class TestParseErrorCode(BaseTest):
("value_error", "ValueError", CohortErrorCode.UNKNOWN),
("clickhouse_regex", "ClickHouseRegexError", CohortErrorCode.INVALID_REGEX),
("clickhouse_memory", "ClickHouseMemoryError", CohortErrorCode.MEMORY_LIMIT),
+ ("clickhouse_too_many_bytes", "ClickHouseTooManyBytesError", CohortErrorCode.DATA_LIMIT),
("clickhouse_timeout", "ClickHouseTimeoutError", CohortErrorCode.TIMEOUT),
("clickhouse_type", "ClickHouseTypeError", CohortErrorCode.INCOMPATIBLE_TYPES),
("generic_exception", "Exception", CohortErrorCode.UNKNOWN),
@@ -1268,6 +1270,7 @@ class TestParseErrorCode(BaseTest):
clickhouse_code_names = {
"ClickHouseRegexError": "CANNOT_COMPILE_REGEXP",
"ClickHouseMemoryError": "MEMORY_LIMIT_EXCEEDED",
+ "ClickHouseTooManyBytesError": "TOO_MANY_BYTES",
"ClickHouseTimeoutError": "TIMEOUT_EXCEEDED",
"ClickHouseTypeError": "NO_COMMON_TYPE",
}
@@ -1287,6 +1290,7 @@ class TestGetFriendlyErrorMessage(BaseTest):
(CohortErrorCode.INTERRUPTED, "interrupted"),
(CohortErrorCode.TIMEOUT, "terminated for taking too long"),
(CohortErrorCode.MEMORY_LIMIT, "terminated for using too much memory"),
+ (CohortErrorCode.DATA_LIMIT, "reading too much data"),
(CohortErrorCode.QUERY_SIZE, "query that was too large"),
(CohortErrorCode.VALIDATION_ERROR, "an error occurred"),
(CohortErrorCode.INVALID_REGEX, "invalid regular expression"),
@@ -1300,6 +1304,23 @@ class TestGetFriendlyErrorMessage(BaseTest):
assert message is not None
self.assertIn(expected_substring, message.lower())
+ @parameterized.expand(
+ [
+ (CohortErrorCode.CAPACITY, "system was busy"),
+ (CohortErrorCode.INTERRUPTED, "interrupted"),
+ ]
+ )
+ def test_get_friendly_error_message_drops_the_retry_promise_when_nothing_will_retry(
+ self, error_code: str, expected_substring: str
+ ):
+ message = get_friendly_error_message(error_code, will_retry=False)
+ assert message is not None
+ self.assertIn(expected_substring, message.lower())
+ # Only the dynamic recalculation scheduler retries, so a cohort it never picks up must not
+ # be told to wait for one.
+ self.assertNotIn("automatically retry", message.lower())
+ self.assertIn("automatically retry", ERROR_CODE_MESSAGES[error_code].lower())
+
def test_get_friendly_error_message_none(self):
self.assertIsNone(get_friendly_error_message(None))
diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.py
index 6c4adba377a8..b67a96467f51 100644
--- a/products/cohorts/backend/models/util.py
+++ b/products/cohorts/backend/models/util.py
@@ -74,6 +74,7 @@ class CohortErrorCode(StrEnum):
INTERRUPTED = "interrupted"
TIMEOUT = "timeout"
MEMORY_LIMIT = "memory_limit"
+ DATA_LIMIT = "data_limit"
QUERY_SIZE = "query_size"
VALIDATION_ERROR = "validation_error"
INVALID_REGEX = "invalid_regex"
@@ -92,6 +93,7 @@ ERROR_CODE_MESSAGES: dict[str, str] = {
CohortErrorCode.INTERRUPTED: "Calculation was interrupted. It will automatically retry.",
CohortErrorCode.TIMEOUT: "Cohort calculation was terminated for taking too long.",
CohortErrorCode.MEMORY_LIMIT: "Cohort calculation was terminated for using too much memory.",
+ CohortErrorCode.DATA_LIMIT: "Cohort calculation was terminated for reading too much data. Narrow the matching criteria, for example to a shorter date range.",
CohortErrorCode.QUERY_SIZE: "The matching criteria produced a query that was too large.",
CohortErrorCode.INVALID_REGEX: "This cohort contains an invalid regular expression. Please check your regex syntax in the matching criteria.",
CohortErrorCode.NO_PROPERTIES: "This cohort has no matching criteria defined. Please add at least one.",
@@ -102,9 +104,24 @@ ERROR_CODE_MESSAGES: dict[str, str] = {
}
-def get_friendly_error_message(error_code: str | None) -> str | None:
+# Each of these codes ends in an instruction a static cohort cannot follow. CAPACITY and
+# INTERRUPTED promise a retry that only the dynamic recalculation scheduler makes good on: the
+# periodic queue excludes static cohorts, and the stuck-cohort sweeper only matches one still
+# marked is_calculating. FLAG_CHANGED asks for the calculation to be run again, but a static
+# cohort is populated once from the source it was created with. A cohort that nothing will re-run
+# needs the same reason without the instruction.
+NO_RETRY_ERROR_CODE_MESSAGES: dict[str, str] = {
+ CohortErrorCode.CAPACITY: "The system was busy when this cohort was scheduled to calculate.",
+ CohortErrorCode.INTERRUPTED: "Calculation was interrupted before it finished.",
+ CohortErrorCode.FLAG_CHANGED: "The feature flag changed while this cohort was being populated. Create a new cohort from the flag to snapshot it again.",
+}
+
+
+def get_friendly_error_message(error_code: str | None, *, will_retry: bool = True) -> str | None:
if error_code is None:
return None
+ if not will_retry and error_code in NO_RETRY_ERROR_CODE_MESSAGES:
+ return NO_RETRY_ERROR_CODE_MESSAGES[error_code]
return ERROR_CODE_MESSAGES.get(error_code, ERROR_CODE_MESSAGES[CohortErrorCode.UNKNOWN])
@@ -113,6 +130,7 @@ def get_friendly_error_message(error_code: str | None) -> str | None:
_CLICKHOUSE_ERROR_MAPPING: dict[str, CohortErrorCode] = {
"cannot_compile_regexp": CohortErrorCode.INVALID_REGEX,
"memory_limit_exceeded": CohortErrorCode.MEMORY_LIMIT,
+ "too_many_bytes": CohortErrorCode.DATA_LIMIT,
"timeout_exceeded": CohortErrorCode.TIMEOUT,
"no_common_type": CohortErrorCode.INCOMPATIBLE_TYPES,
}
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 d4536dbae6f5..e179d6fc7eda 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
@@ -1388,6 +1388,108 @@
'''
# ---
# name: TestFeatureFlag.test_creating_static_cohort.24
+ '''
+ SELECT "posthog_team"."id",
+ "posthog_team"."uuid",
+ "posthog_team"."organization_id",
+ "posthog_team"."parent_team_id",
+ "posthog_team"."project_id",
+ "posthog_team"."api_token",
+ "posthog_team"."app_urls",
+ "posthog_team"."name",
+ "posthog_team"."slack_incoming_webhook",
+ "posthog_team"."created_at",
+ "posthog_team"."updated_at",
+ "posthog_team"."anonymize_ips",
+ "posthog_team"."completed_snippet_onboarding",
+ "posthog_team"."has_completed_onboarding_for",
+ "posthog_team"."onboarding_tasks",
+ "posthog_team"."ingested_event",
+ "posthog_team"."ingested_production_event",
+ "posthog_team"."ingested_production_event_last_checked_at",
+ "posthog_team"."person_processing_opt_out",
+ "posthog_team"."secret_api_token",
+ "posthog_team"."secret_api_token_backup",
+ "posthog_team"."session_recording_opt_in",
+ "posthog_team"."session_recording_sample_rate",
+ "posthog_team"."session_recording_minimum_duration_milliseconds",
+ "posthog_team"."session_recording_linked_flag",
+ "posthog_team"."session_recording_network_payload_capture_config",
+ "posthog_team"."session_recording_masking_config",
+ "posthog_team"."session_recording_url_trigger_config",
+ "posthog_team"."session_recording_url_blocklist_config",
+ "posthog_team"."session_recording_event_trigger_config",
+ "posthog_team"."session_recording_trigger_match_type_config",
+ "posthog_team"."session_recording_trigger_groups",
+ "posthog_team"."session_replay_config",
+ "posthog_team"."session_recording_retention_period",
+ "posthog_team"."event_retention_months",
+ "posthog_team"."conversations_enabled",
+ "posthog_team"."conversations_settings",
+ "posthog_team"."proactive_tasks_enabled",
+ "posthog_team"."survey_config",
+ "posthog_team"."surveys_opt_in",
+ "posthog_team"."product_tours_opt_in",
+ "posthog_team"."capture_console_log_opt_in",
+ "posthog_team"."capture_performance_opt_in",
+ "posthog_team"."capture_dead_clicks",
+ "posthog_team"."autocapture_opt_out",
+ "posthog_team"."autocapture_web_vitals_opt_in",
+ "posthog_team"."autocapture_web_vitals_allowed_metrics",
+ "posthog_team"."autocapture_exceptions_opt_in",
+ "posthog_team"."autocapture_exceptions_errors_to_ignore",
+ "posthog_team"."logs_settings",
+ "posthog_team"."llm_gateway_enabled_at",
+ "posthog_team"."llm_gateway_revoked_at",
+ "posthog_team"."llm_gateway_overspend_allowance_usd",
+ "posthog_team"."heatmaps_opt_in",
+ "posthog_team"."receive_org_level_activity_logs",
+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
+ "posthog_team"."web_analytics_pre_aggregated_tables_version",
+ "posthog_team"."flags_persistence_default",
+ "posthog_team"."feature_flag_confirmation_enabled",
+ "posthog_team"."feature_flag_confirmation_message",
+ "posthog_team"."default_evaluation_environments_enabled",
+ "posthog_team"."require_evaluation_environment_tags",
+ "posthog_team"."default_evaluation_contexts_enabled",
+ "posthog_team"."require_evaluation_contexts",
+ "posthog_team"."session_recording_version",
+ "posthog_team"."signup_token",
+ "posthog_team"."is_demo",
+ "posthog_team"."access_control",
+ "posthog_team"."week_start_day",
+ "posthog_team"."inject_web_apps",
+ "posthog_team"."test_account_filters",
+ "posthog_team"."test_account_filters_default_checked",
+ "posthog_team"."path_cleaning_filters",
+ "posthog_team"."timezone",
+ "posthog_team"."data_attributes",
+ "posthog_team"."person_display_name_properties",
+ "posthog_team"."live_events_columns",
+ "posthog_team"."recording_domains",
+ "posthog_team"."human_friendly_comparison_periods",
+ "posthog_team"."cookieless_server_hash_mode",
+ "posthog_team"."primary_dashboard_id",
+ "posthog_team"."default_data_theme",
+ "posthog_team"."extra_settings",
+ "posthog_team"."modifiers",
+ "posthog_team"."correlation_config",
+ "posthog_team"."session_recording_retention_period_days",
+ "posthog_team"."external_data_workspace_id",
+ "posthog_team"."external_data_workspace_last_synced_at",
+ "posthog_team"."api_query_rate_limit",
+ "posthog_team"."drop_events_older_than",
+ "posthog_team"."base_currency",
+ "posthog_team"."experiment_recalculation_time",
+ "posthog_team"."default_experiment_confidence_level",
+ "posthog_team"."default_experiment_stats_method",
+ "posthog_team"."business_model"
+ FROM "posthog_team"
+ WHERE "posthog_team"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestFeatureFlag.test_creating_static_cohort.25
'''
SELECT "posthog_cohort"."id",
"posthog_cohort"."name",
@@ -1424,7 +1526,7 @@
LIMIT 21
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.25
+# name: TestFeatureFlag.test_creating_static_cohort.26
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1526,7 +1628,7 @@
LIMIT 21
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.26
+# name: TestFeatureFlag.test_creating_static_cohort.27
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -1573,7 +1675,7 @@
LIMIT 21
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.27
+# name: TestFeatureFlag.test_creating_static_cohort.28
'''
SELECT "posthog_cohortcalculationhistory"."id",
"posthog_cohortcalculationhistory"."team_id",
@@ -1594,7 +1696,7 @@
LIMIT 1
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.28
+# name: TestFeatureFlag.test_creating_static_cohort.29
'''
SELECT "posthog_experiment"."id",
"posthog_experiment"."name",
@@ -1638,17 +1740,6 @@
WHERE "posthog_experiment"."exposure_cohort_id" = 99999
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.29
- '''
- /* user_id:0 celery:posthog.tasks.calculate_cohort.insert_cohort_from_feature_flag */
- SELECT person_id
- FROM person_static_cohort
- WHERE team_id = 99999
- AND cohort_id = 99999
- AND person_id IN ['00000000-0000-4000-8000-000000000000']
- GROUP BY person_id
- '''
-# ---
# name: TestFeatureFlag.test_creating_static_cohort.3
'''
SELECT "posthog_project"."updated_at",
@@ -1665,6 +1756,17 @@
'''
# ---
# name: TestFeatureFlag.test_creating_static_cohort.30
+ '''
+ /* user_id:0 celery:posthog.tasks.calculate_cohort.insert_cohort_from_feature_flag */
+ SELECT person_id
+ FROM person_static_cohort
+ WHERE team_id = 99999
+ AND cohort_id = 99999
+ AND person_id IN ['00000000-0000-4000-8000-000000000000']
+ GROUP BY person_id
+ '''
+# ---
+# name: TestFeatureFlag.test_creating_static_cohort.31
'''
/* user_id:0 request:_snapshot_ */
SELECT persons.id AS 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 65f1075aee0d..c01889ee0c73 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -9479,6 +9479,30 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
cohort.refresh_from_db()
self.assertEqual(cohort.count, 3)
+ # Every static population path records one row per attempt, so a flag-backed cohort's
+ # calculation history is not just its failures.
+ history = CohortCalculationHistory.objects.get(cohort=cohort)
+ self.assertIsNone(history.error)
+ self.assertEqual(history.count, 3)
+ self.assertIsNotNone(history.finished_at)
+
+ @patch("posthog.api.cohort.batch_evaluate_flag_for_team")
+ def test_history_write_failure_does_not_fail_a_populated_cohort(self, mock_batch_evaluate):
+ self._create_flag()
+ person = _create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"}, immediate=True)
+ flush_persons_and_events()
+ cohort = self._create_static_cohort()
+
+ mock_batch_evaluate.return_value = self._page([str(person.uuid)])
+
+ with patch.object(CohortCalculationHistory.objects, "create", side_effect=IntegrityError("no row for you")):
+ get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)
+
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.count, 1)
+ self.assertFalse(cohort.is_calculating)
+ self.assertEqual(cohort.errors_calculating, 0)
+
@patch("posthog.api.cohort.batch_evaluate_flag_for_team")
def test_non_advancing_cursor_fails_instead_of_looping(self, mock_batch_evaluate):
self._create_flag()
@@ -9581,10 +9605,11 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(cohort.errors_calculating, 1)
history = CohortCalculationHistory.objects.get(cohort=cohort)
self.assertEqual(history.error_code, CohortErrorCode.FLAG_CHANGED)
- self.assertEqual(
- get_friendly_error_message(history.error_code),
- "The feature flag changed while this cohort was being calculated. Please run the calculation again.",
- )
+ # This path only populates static cohorts, whose banner has no Retry action, so the stored
+ # copy must not ask for a re-run.
+ assert history.error is not None
+ self.assertNotIn("run the calculation again", history.error)
+ self.assertEqual(history.error, get_friendly_error_message(history.error_code, will_retry=False))
@patch("posthog.api.cohort.time.sleep")
@patch("posthog.api.cohort.batch_evaluate_flag_for_team")