: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(hogql): reject deleted cohorts when building a cohort property filter (#116790)
Juraj Majerikee932fdecf50
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.pyindex b24b7c397238..a84e2527ed49 100644--- a/posthog/hogql/property.py+++ b/posthog/hogql/property.py@@ -1707,10 +1707,12 @@ def property_to_expr(if not isinstance(property.value, (str, int)):raise ValidationError("Cohort property value must be a cohort ID")try:- cohort = Cohort.objects.get(team__project_id=team.project_id, id=property.value)+ cohort = Cohort.objects.get(team__project_id=team.project_id, id=property.value, deleted=False)except Cohort.DoesNotExist:# The id comes from the request, so a deleted or foreign cohort must read as- # bad input rather than escaping as an unhandled DoesNotExist.+ # bad input rather than escaping as an unhandled DoesNotExist. `cohort()` and the+ # IN COHORT transform skip deleted cohorts too, so the filter must fail here, not+ # at print time when the whole query has already been built.raise QueryError(f"Cohort {property.value} does not exist")# Kludge: negation is outdated but still used in placesnegated = property.negation or property.operator == PropertyOperator.NOT_IN.valuediff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.pyindex e6d27116e9ba..b168cd197cf1 100644--- a/posthog/hogql/test/test_property.py+++ b/posthog/hogql/test/test_property.py@@ -1125,9 +1125,13 @@ class TestProperty(BaseTest):),)- def test_cohort_filter_missing_cohort(self):- with self.assertRaisesMessage(QueryError, "Cohort 2137 does not exist"):- self._property_to_expr({"type": "cohort", "key": "id", "value": 2137}, self.team)+ @parameterized.expand([("missing", False), ("deleted", True)])+ def test_cohort_filter_missing_cohort(self, _name: str, deleted: bool):+ cohort_id = 2137+ if deleted:+ cohort_id = Cohort.objects.create(team=self.team, name="gone", groups=[], deleted=True).pk+ with self.assertRaisesMessage(QueryError, f"Cohort {cohort_id} does not exist"):+ self._property_to_expr({"type": "cohort", "key": "id", "value": cohort_id}, self.team)def test_person_scope(self):self.assertEqual(diff --git a/products/experiments/backend/test/test_session_context_api.py b/products/experiments/backend/test/test_session_context_api.pyindex 25e4ba3338de..928b5a1568ce 100644--- a/products/experiments/backend/test/test_session_context_api.py+++ b/products/experiments/backend/test/test_session_context_api.py@@ -29,6 +29,7 @@ from products.access_control.backend.facade.api import upsert_property_access_cofrom products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInputfrom products.access_control.backend.models.access_control import AccessControlfrom products.actions.backend.models.action import Action+from products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetricfrom products.experiments.backend.session_context import (MAX_SESSION_CONTEXT_BATCH,@@ -553,17 +554,22 @@ class TestSessionExperimentContext(ClickhouseTestMixin, APILicensedTest):assert results[0]["variant"] == "test"assert results[0]["first_exposure_timestamp"] is None- def test_unresolvable_property_filter_fails_soft(self) -> None:+ @parameterized.expand([("foreign_cohort", False), ("deleted_cohort", True)])+ def test_unresolvable_property_filter_fails_soft(self, _name: str, deleted: bool) -> None:self._create_recording()- # A duplicated experiment can carry a cohort id from its source project; resolving that- # filter raises. One such experiment must not 500 the endpoint — it degrades to- # stamped-property evidence with no exposure moment.+ # A duplicated experiment can carry a cohort id from its source project, and a cohort+ # can be deleted after the experiment launched. Resolving either filter raises. One such+ # experiment must not fail the endpoint — it degrades to stamped-property evidence with+ # no exposure moment.+ cohort_id = 999999+ if deleted:+ cohort_id = Cohort.objects.create(team=self.team, name="gone", groups=[], deleted=True).pkself._create_experiment(exposure_criteria={"exposure_config": {"kind": "ExperimentEventExposureConfig","event": "checkout started",- "properties": [{"key": "id", "value": 999999, "type": "cohort"}],+ "properties": [{"key": "id", "value": cohort_id, "type": "cohort"}],}})