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(experiments): skip precompute while a referenced cohort's first calculation is running (#72878)

Juraj Majerikfa70e2a09b47
diff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
index d36ada3c0371..5a5c9b28efeb 100644
--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
@@ -43,6 +43,7 @@ from products.experiments.backend.hogql_queries.experiment_query_builder import
from products.experiments.backend.hogql_queries.experiment_query_runner import (
experiment_has_min_runtime_for_precomputation,
experiment_precompute_ttl_schedule,
+ has_uncalculated_cohorts,
)
from products.experiments.backend.hogql_queries.exposure_query_logic import get_entity_key
from products.experiments.backend.models.experiment import Experiment
@@ -164,6 +165,7 @@ class ExperimentExposuresQueryRunner(QueryRunner):
self.experiment.start_date,
self.experiment.end_date,
)
+ and not has_uncalculated_cohorts(self.team, self.exposure_criteria)
):
try:
with tags_context(experiment_query_surface="precompute_build", experiment_precompute_table="exposures"):
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 80674958a8b6..e70c8777f4f6 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -1,10 +1,13 @@
import uuid
from datetime import UTC, datetime, timedelta
from functools import cached_property
-from typing import Optional
+from typing import Any, Optional
+
+from django.db.models import Q
import structlog
import posthoganalytics
+from pydantic import BaseModel
from rest_framework.exceptions import ValidationError
from posthog.schema import (
@@ -34,6 +37,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import QueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.models.team.team import Team
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
LazyComputationResult,
@@ -42,6 +46,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
ensure_precomputed,
parse_ttl_schedule,
)
+from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY, get_baseline_variant_key
from products.experiments.backend.hogql_queries.base_query_utils import experiment_window, experiment_window_end
from products.experiments.backend.hogql_queries.cuped_config import get_cuped_config
@@ -146,6 +151,53 @@ def experiment_has_min_runtime_for_precomputation(
return (effective_end - start_date).total_seconds() >= MIN_PRECOMPUTATION_DURATION_SECONDS
+def _collect_cohort_ids(obj: Any) -> set[int]:
+ """Cohort IDs referenced anywhere in a filter/criteria/metric JSON structure."""
+ ids: set[int] = set()
+ if isinstance(obj, dict):
+ if obj.get("type") in ("cohort", "static-cohort", "precalculated-cohort"):
+ value = obj.get("value")
+ if isinstance(value, int | str):
+ try:
+ ids.add(int(value))
+ except ValueError:
+ pass
+ for nested in obj.values():
+ ids |= _collect_cohort_ids(nested)
+ elif isinstance(obj, list):
+ for item in obj:
+ ids |= _collect_cohort_ids(item)
+ return ids
+
+
+def has_uncalculated_cohorts(team: Team, *filter_sources: Any) -> bool:
+ """True when any cohort referenced in the given filter structures hasn't finished its
+ first materialization (dynamic: no completed version; static: initial population running).
+
+ Queries against such a cohort read its partially-inserted membership — they load fine
+ but undercount, and with a skew determined by insertion order. A precompute build in
+ that window freezes the torn snapshot for the frozen-band TTL (60 days), so precompute
+ must be skipped until the first calculation lands. Cohorts with a completed version are
+ safe even mid-recalculation: reads pin the last complete version, and cohorts recalculate
+ every ~15 minutes, so gating on is_calculating would disable precompute permanently.
+ """
+ ids: set[int] = set()
+ for source in filter_sources:
+ if source is None:
+ continue
+ if isinstance(source, BaseModel):
+ source = source.model_dump()
+ ids |= _collect_cohort_ids(source)
+ if not ids:
+ return False
+ return Cohort.objects.filter(
+ Q(is_static=False, version__isnull=True) | Q(is_static=True, is_calculating=True),
+ team__project_id=team.project_id,
+ pk__in=ids,
+ deleted=False,
+ ).exists()
+
+
class ExperimentQueryRunner(QueryRunner):
query: ExperimentQuery
cached_response: CachedExperimentQueryResponse
@@ -341,10 +393,13 @@ class ExperimentQueryRunner(QueryRunner):
if not self._team_experiments_config.experiment_precomputation_enabled:
return False
- return experiment_has_min_runtime_for_precomputation(
+ if not experiment_has_min_runtime_for_precomputation(
self.experiment.start_date,
self.experiment.end_date,
- )
+ ):
+ return False
+
+ return not has_uncalculated_cohorts(self.team, self.experiment.exposure_criteria, self.metric)
def _precompute_skip_reason(self) -> Optional[str]:
"""Why precompute was not used, for the query-performance UI. None when it was attempted."""
@@ -359,6 +414,8 @@ class ExperimentQueryRunner(QueryRunner):
self.experiment.end_date,
):
return "min_runtime"
+ if has_uncalculated_cohorts(self.team, self.experiment.exposure_criteria, self.metric):
+ return "cohort_not_calculated"
if self.is_data_warehouse_query:
return "data_warehouse"
if self.group_type_index is not None:
diff --git a/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py b/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
index 0c2332adfff0..3b816e5aa0d4 100644
--- a/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
+++ b/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
@@ -8,10 +8,12 @@ from parameterized import parameterized
from posthog.schema import EventsNode, ExperimentMeanMetric, ExperimentQuery, PrecomputationMode
+from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.hogql_queries.experiment_query_runner import (
MIN_PRECOMPUTATION_DURATION_SECONDS,
ExperimentQueryRunner,
experiment_has_min_runtime_for_precomputation,
+ has_uncalculated_cohorts,
)
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
@@ -105,3 +107,71 @@ class TestShouldPrecomputeRespectsGate(ExperimentQueryRunnerBaseTest):
self._disable_precomputation()
runner = self._build_runner(experiment)
assert runner._should_precompute() is False
+
+
+def _cohort_exposure_criteria(cohort_id: int) -> dict:
+ return {
+ "exposure_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "$feature_flag_called",
+ "properties": [{"key": "id", "type": "cohort", "value": cohort_id, "operator": "in"}],
+ }
+ }
+
+
+@override_settings(IN_UNIT_TESTING=True)
+class TestUncalculatedCohortGate(ExperimentQueryRunnerBaseTest):
+ @parameterized.expand(
+ [
+ # name, is_static, version, is_calculating, expected
+ ("dynamic_never_calculated", False, None, True, True),
+ ("dynamic_calculated", False, 1, False, False),
+ ("dynamic_mid_recalculation", False, 3, True, False),
+ ("static_populating", True, None, True, True),
+ ("static_populated", True, None, False, False),
+ ]
+ )
+ def test_cohort_states(self, _name, is_static, version, is_calculating, expected):
+ cohort = Cohort.objects.create(team=self.team, name="test cohort", is_static=is_static)
+ Cohort.objects.filter(pk=cohort.pk).update(version=version, is_calculating=is_calculating)
+
+ assert has_uncalculated_cohorts(self.team, _cohort_exposure_criteria(cohort.pk)) is expected
+
+ def test_no_cohort_references_returns_false(self):
+ criteria = {
+ "exposure_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "$feature_flag_called",
+ "properties": [{"key": "email", "type": "person", "value": "@x.com", "operator": "icontains"}],
+ }
+ }
+ assert has_uncalculated_cohorts(self.team, criteria, None) is False
+
+ def test_finds_cohort_in_pydantic_metric(self):
+ cohort = Cohort.objects.create(team=self.team, name="test cohort")
+ metric = ExperimentMeanMetric(
+ source=EventsNode(event="purchase", properties=[{"key": "id", "type": "cohort", "value": cohort.pk}])
+ )
+ assert has_uncalculated_cohorts(self.team, metric) is True
+
+ @freeze_time("2026-04-30T12:00:00Z")
+ def test_should_precompute_waits_for_first_cohort_calculation(self):
+ feature_flag = self.create_feature_flag()
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2026, 4, 29, 0, 0, 0), # over the duration threshold
+ )
+ cohort = Cohort.objects.create(team=self.team, name="fresh cohort", is_calculating=True)
+ experiment.exposure_criteria = _cohort_exposure_criteria(cohort.pk)
+ experiment.save()
+ self._enable_precomputation()
+
+ metric = ExperimentMeanMetric(source=EventsNode(event="purchase"))
+ query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)
+ runner = ExperimentQueryRunner(query=query, team=self.team)
+ assert runner._should_precompute() is False
+ assert runner._precompute_skip_reason() == "cohort_not_calculated"
+
+ Cohort.objects.filter(pk=cohort.pk).update(version=1, is_calculating=False)
+ assert runner._should_precompute() is True
+ assert runner._precompute_skip_reason() is None