: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(cohorts): reject trends actor cohorts saved without a day (#75624)
posthog[bot]5d45c0e29083
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex a8648cdc9086..cea3884677ef 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -98,6 +98,7 @@ from products.cohorts.backend.models.util import (cohort_filters_have_values,get_all_cohort_dependencies,get_friendly_error_message,+ validate_actors_query_for_cohort,)from products.cohorts.backend.models.validation import CohortTypeValidationSerializerfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -1022,6 +1023,7 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializraise ValidationError("Query must be a dictionary.")if query.get("kind") == "ActorsQuery":ActorsQuery.model_validate(query)+ validate_actors_query_for_cohort(query)elif query.get("kind") == "HogQLQuery":HogQLQuery.model_validate(query)else:diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex 54ee55eb445b..e4f402fac007 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -3114,6 +3114,39 @@ [email protected],)self.assertEqual(response.status_code, 400, response.content)+ @parameterized.expand(+ [+ ("time_series_without_day", None, None),+ ("total_value_with_day", "BoldNumber", "2026-07-01"),+ ]+ )+ def test_creating_static_cohort_from_trends_actors_with_invalid_day_is_rejected(+ self, _name: str, display: str | None, day: str | None+ ) -> None:+ trends_filter = {"display": display} if display else None+ actors_source: dict[str, Any] = {+ "kind": "InsightActorsQuery",+ "source": {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ **({"trendsFilter": trends_filter} if trends_filter else {}),+ },+ **({"day": day} if day else {}),+ }+ response = self.client.post(+ f"/api/projects/{self.team.id}/cohorts",+ data={+ "name": "cohort A",+ "is_static": True,+ "query": {+ "kind": "ActorsQuery",+ "select": ["person"],+ "source": actors_source,+ },+ },+ )+ self.assertEqual(response.status_code, 400, response.content)+@patch("posthog.api.cohort.report_user_action")def test_creating_with_query_and_fields(self, patch_capture):_create_person(diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_actors_query_builder.py b/posthog/hogql_queries/insights/trends/test/test_trends_actors_query_builder.pyindex 3c44895f6f07..833d939c6e86 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends_actors_query_builder.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends_actors_query_builder.py@@ -28,6 +28,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import MAX_SELECT_RETURNED_ROWSfrom posthog.hogql.context import HogQLContext+from posthog.hogql.errors import QueryErrorfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_ast@@ -232,6 +233,27 @@ class TestTrendsActorsQueryBuilder(BaseTest):"greaterOrEquals(timestamp, toDateTime('2022-06-07 22:00:00.000000')), lessOrEquals(timestamp, toDateTime('2022-06-15 21:59:59.999999'))",)+ @parameterized.expand(+ [+ ("time_series_without_day", None, None, "A `day` is required"),+ ("total_value_with_day", ChartDisplayType.BOLD_NUMBER, "2023-05-08", "A `day` is forbidden"),+ ]+ )+ def test_invalid_time_frame_raises_query_error(+ self,+ _name: str,+ display: ChartDisplayType | None,+ time_frame: str | None,+ expected_error: str,+ ) -> None:+ trends_query = default_query.model_copy(+ update={"trendsFilter": TrendsFilter(display=display)} if display else {},+ deep=True,+ )++ with self.assertRaisesRegex(QueryError, expected_error):+ self._get_date_where_sql(trends_query=trends_query, time_frame=time_frame)+def test_date_range_total_value_compare_previous(self):self.team.timezone = "Europe/Berlin"trends_query = default_query.model_copy(diff --git a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.pyindex af2bea75db97..31ff390881d6 100644--- a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py+++ b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py@@ -21,6 +21,7 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import LimitContext+from posthog.hogql.errors import QueryErrorfrom posthog.hogql.parser import parse_exprfrom posthog.hogql.property import action_to_expr, property_to_exprfrom posthog.hogql.timings import HogQLTimings@@ -419,17 +420,15 @@ class TrendsActorsQueryBuilder:actors_to_op: ast.CompareOperationOp = ast.CompareOperationOp.Ltif self.is_total_value:- assert self.time_frame is None, (- "A `day` is forbidden for trends actors queries with total value aggregation"- )+ if self.time_frame is not None:+ raise QueryError("A `day` is forbidden for trends actors queries with total value aggregation")actors_from = query_fromactors_to = query_toactors_to_op = ast.CompareOperationOp.LtEqelse:- assert self.time_frame is not None, (- "A `day` is required for trends actors queries without total value aggregation"- )+ if self.time_frame is None:+ raise QueryError("A `day` is required for trends actors queries without total value aggregation")# use previous day/week/... for time_frameif self.is_compare_previous:diff --git a/products/cohorts/backend/models/test/test_util.py b/products/cohorts/backend/models/test/test_util.pyindex 8bcf2c21add0..6f99e403a56e 100644--- a/products/cohorts/backend/models/test/test_util.py+++ b/products/cohorts/backend/models/test/test_util.py@@ -1,7 +1,10 @@+from typing import Any+from posthog.test.base import BaseTest, _create_person, flush_persons_and_eventsfrom unittest.mock import MagicMock, patchfrom django.db import DEFAULT_DB_ALIAS, OperationalError+from django.test import SimpleTestCasefrom clickhouse_driver.errors import SocketTimeoutErrorfrom parameterized import parameterized@@ -37,6 +40,7 @@ from products.cohorts.backend.models.util import (print_cohort_hogql_query,simplified_cohort_filter_properties,sort_cohorts_topologically,+ validate_actors_query_for_cohort,)MISSING_COHORT_ID = 12345@@ -51,6 +55,40 @@ def _create_cohort(**kwargs):return cohort+class TestCohortQueryValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("time_series_trends_without_day", None, None, True),+ ("time_series_trends_with_empty_day", None, "", True),+ ("time_series_trends_with_whitespace_day", None, " ", True),+ ("time_series_trends_with_malformed_day", None, "not-a-date", True),+ ("time_series_trends_with_integer_day", None, 0, True),+ ("time_series_trends_with_day", None, "2026-07-01", False),+ ("total_value_trends_without_day", "BoldNumber", None, False),+ ("total_value_trends_with_day", "BoldNumber", "2026-07-01", True),+ ]+ )+ def test_validate_actors_query_for_cohort_requires_valid_day(+ self, _name: str, display: str | None, day: str | int | None, should_raise: bool+ ) -> None:+ insight: dict[str, Any] = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview"}],+ }+ if display:+ insight["trendsFilter"] = {"display": display}+ source: dict[str, Any] = {"kind": "InsightActorsQuery", "source": insight}+ if day is not None:+ source["day"] = day+ query = {"kind": "ActorsQuery", "select": ["person"], "source": source}++ if should_raise:+ with self.assertRaises(DRFValidationError):+ validate_actors_query_for_cohort(query)+ else:+ validate_actors_query_for_cohort(query)++class TestCohortUtils(BaseTest):def test_simplified_cohort_filter_properties_static_cohort(self):_create_person(diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.pyindex fa643ce683df..bb2ec59053d9 100644--- a/products/cohorts/backend/models/util.py+++ b/products/cohorts/backend/models/util.py@@ -46,7 +46,7 @@ from posthog.models.person.sql import (PERSON_STATIC_COHORT_TABLE,)from posthog.models.property import Property, PropertyGroup-from posthog.schema_enums import PersonsOnEventsMode, ProductKey+from posthog.schema_enums import ChartDisplayType, PersonsOnEventsMode, ProductKeyfrom posthog.schema_migrations.upgrade import upgradefrom products.actions.backend.models.action import Action@@ -325,6 +325,53 @@ def format_person_query(cohort: Cohort, index: int) -> tuple[str, dict[str, Any]return _prefix_cohort_hogql_params(cohort_query, cohort_context.values, cohort=cohort, index=index)+def validate_actors_query_for_cohort(query_dict: dict[str, Any]) -> None:+ """Reject actor queries that would only fail once the populate task compiles them.++ Pydantic validation is not enough here: `day` is optional on `InsightActorsQuery`, but a+ time-series trends source cannot be compiled without it, so the cohort would save fine and+ then raise for good in the background populate task.+ """+ if query_dict.get("kind") != "ActorsQuery":+ return++ source = query_dict.get("source")+ if not isinstance(source, dict) or source.get("kind") != "InsightActorsQuery":+ return++ insight = source.get("source")+ if not isinstance(insight, dict) or insight.get("kind") != "TrendsQuery":+ return++ from posthog.hogql_queries.insights.trends.display import ( # noqa: PLC0415 — keeps posthog.schema off the startup path+ TrendsDisplay,+ )++ trends_filter = insight.get("trendsFilter")+ raw_display = trends_filter.get("display") if isinstance(trends_filter, dict) else None+ try:+ display = ChartDisplayType(raw_display) if raw_display else None+ except ValueError:+ return # Pydantic validation owns unknown display types+ day = source.get("day")+ if TrendsDisplay(display).is_total_value():+ if day is not None:+ raise ValidationError("Do not provide a day for a total value trends insight.")+ return++ invalid_day_message = (+ "Provide a valid day for this time series trends insight. "+ "To choose a day in PostHog, open the insight and click a data point."+ )+ if not isinstance(day, str):+ raise ValidationError(invalid_day_message)++ try:+ parser.parse(day)+ except (ValueError, OverflowError):+ raise ValidationError(invalid_day_message) from None++def _sanitize_query_for_cohort(query_dict: dict) -> dict:"""Strip fields unnecessary for cohort population.