: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): answer 400 when a query filters on a missing cohort (#99500)
Thomas Obermüller6a248d5a17d9
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.pyindex e15930fb204f..ef2ae8acf88e 100644--- a/posthog/hogql/property.py+++ b/posthog/hogql/property.py@@ -1570,7 +1570,12 @@ def property_to_expr(raise Exception("Can not convert cohort property to expression without team")if not isinstance(property.value, (str, int)):raise ValidationError("Cohort property value must be a cohort ID")- cohort = Cohort.objects.get(team__project_id=team.project_id, id=property.value)+ try:+ cohort = Cohort.objects.get(team__project_id=team.project_id, id=property.value)+ 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.+ raise QueryError(f"Cohort {property.value} does not exist")return ast.CompareOperation(left=ast.Field(chain=["id" if scope == "person" else "person_id"]),op=(diff --git a/posthog/hogql/test/test_property.py b/posthog/hogql/test/test_property.pyindex 46ca8d91cce9..cb36858f266b 100644--- a/posthog/hogql/test/test_property.py+++ b/posthog/hogql/test/test_property.py@@ -982,6 +982,10 @@ class TestProperty(BaseTest):self._parse_expr(f"person_id IN COHORT {cohort.pk}"),)+ 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)+def test_person_scope(self):self.assertEqual(self._property_to_expr(