: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(retention): reject warehouse timestamp columns that aren't dates (#85297)
Thomas Obermüller10ccec6b047f
diff --git a/posthog/hogql_queries/insights/retention/retention_query_runner.py b/posthog/hogql_queries/insights/retention/retention_query_runner.pyindex 93aade41e821..f25454133fcd 100644--- a/posthog/hogql_queries/insights/retention/retention_query_runner.py+++ b/posthog/hogql_queries/insights/retention/retention_query_runner.py@@ -43,6 +43,7 @@ from posthog.hogql_queries.insights.retention.retention_validation_rules importDisallowCumulativeWith24HourWindows,DisallowGroupAggregationWithDataWarehouse24HourWindows,DisallowPropertyAggregationWith24HourWindows,+ DisallowUnsupportedDataWarehouseTimestampField,)from posthog.hogql_queries.insights.utils.breakdowns import (ALL_USERS_COHORT_ID,@@ -149,6 +150,7 @@ class RetentionQueryRunner(AnalyticsQueryRunner[RetentionQueryResponse]):DisallowGroupAggregationWithDataWarehouse24HourWindows(),DisallowPropertyAggregationWith24HourWindows(),DisallowUnsupportedDataWarehouseSettings(),+ DisallowUnsupportedDataWarehouseTimestampField(),)@cached_propertydiff --git a/posthog/hogql_queries/insights/retention/retention_validation_rules.py b/posthog/hogql_queries/insights/retention/retention_validation_rules.pyindex 77fd39ca3c84..42c4acc14633 100644--- a/posthog/hogql_queries/insights/retention/retention_validation_rules.py+++ b/posthog/hogql_queries/insights/retention/retention_validation_rules.py@@ -2,7 +2,11 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.schema import AggregationType, EntityType, RetentionQuery+from posthog.hogql.database.database import Database+from posthog.hogql.database.models import DateDatabaseField, DateTimeDatabaseField+from posthog.hogql_queries.insights.utils.breakdowns import has_breakdown_filter+from posthog.hogql_queries.insights.utils.data_warehouse_schema_mixin import resolve_warehouse_fieldfrom posthog.hogql_queries.validation.validation import QueryValidationContext@@ -63,6 +67,41 @@ class DisallowGroupAggregationWithDataWarehouse24HourWindows:)+class DisallowUnsupportedDataWarehouseTimestampField:+ """Every interval bucket runs the configured timestamp column through toStartOfInterval, so a column that+ cannot be a datetime fails deep inside ClickHouse, quoting generated SQL the user never wrote. Resolving+ the column type up front turns that into a 400 naming the column they picked.++ An integer is rejected rather than converted because it could hold seconds, milliseconds or microseconds+ since the epoch, and guessing wrong shifts every bucket instead of failing."""++ code = "retention_data_warehouse_timestamp_field_unsupported"++ def validate(self, context: QueryValidationContext[RetentionQuery]) -> None:+ retention_filter = context.query.retentionFilter+ entities = [+ entity+ for entity in (retention_filter.targetEntity, retention_filter.returningEntity)+ if entity is not None and entity.type == EntityType.DATA_WAREHOUSE+ ]+ if not entities:+ return++ database = Database.create_for(team=context.team, user=context.user)+ for entity in entities:+ if not entity.table_name or not entity.timestamp_field:+ # A half-configured entity raises its own error while building the query.+ continue+ field = resolve_warehouse_field(database, entity.table_name, entity.timestamp_field)+ if not isinstance(field, DateTimeDatabaseField | DateDatabaseField):+ raise ValidationError(+ f"{entity.table_name}.{entity.timestamp_field} can't be used as the retention timestamp, "+ "because it isn't a date or datetime column. Pick a different column, "+ "or convert this one in a saved query first.",+ code=self.code,+ )++class DisallowPropertyAggregationWith24HourWindows:"""The 24-hour-window builder never emits the retention_value column that sum/avg aggregation reads in theouter query."""diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py b/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.pyindex ac3218175170..c206f88c4c9c 100644--- a/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py+++ b/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py@@ -13,6 +13,7 @@ from posthog.test.base import ()from parameterized import parameterized+from rest_framework.exceptions import ValidationErrorfrom posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner@@ -253,6 +254,50 @@ class TestRetentionDataWarehouse(ClickhouseTestMixin, APIBaseTest):"returningEntity": entity("renewed"),}+ def _activity_table_with_timestamp_type(self, column_type: str, occurred_at: list[object]) -> str:+ person_ids = self._create_people()+ suffix = "".join(c for c in column_type.lower() if c.isalnum())+ return self._create_data_warehouse_table(+ filename=f"warehouse_activity_ts_{suffix}.csv",+ table_name=f"warehouse_activity_ts_{suffix}",+ header=["id", "person_id", "activity_type", "occurred_at"],+ rows=[+ [1, person_ids["user-1"], "signed_up", occurred_at[0]],+ [2, person_ids["user-2"], "signed_up", occurred_at[1]],+ [3, person_ids["user-1"], "renewed", occurred_at[2]],+ [4, person_ids["user-2"], "renewed", occurred_at[3]],+ ],+ table_columns={+ "id": "Int64",+ "person_id": "UUID",+ "activity_type": "String",+ "occurred_at": column_type,+ },+ )++ @parameterized.expand(+ [+ ("integer", "Int64", [1735722000, 1735725600, 1735815600, 1735905600]),+ (+ "string",+ "String",+ ["2025-01-01 09:00:00", "2025-01-01 10:00:00", "2025-01-02 12:00:00", "2025-01-03 12:00:00"],+ ),+ ]+ )+ def test_non_datetime_timestamp_field_is_rejected(self, _name: str, column_type: str, occurred_at: list[object]):+ # Both types reach toStartOfInterval and fail inside ClickHouse without this check, quoting+ # generated SQL rather than naming the column the user picked.+ table = self._activity_table_with_timestamp_type(column_type, occurred_at)++ with self.assertRaisesMessage(ValidationError, "isn't a date or datetime column"):+ self.run_query(+ query={+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},+ "retentionFilter": self._activity_retention_filter(table),+ }+ )+@snapshot_clickhouse_queriesdef test_retention_data_warehouse_breakdown_by_warehouse_column(self):table, _person_ids = self._activity_breakdown_table()diff --git a/posthog/hogql_queries/insights/utils/data_warehouse_schema_mixin.py b/posthog/hogql_queries/insights/utils/data_warehouse_schema_mixin.pyindex 921839a59a3a..6cb4c1d5be3d 100644--- a/posthog/hogql_queries/insights/utils/data_warehouse_schema_mixin.py+++ b/posthog/hogql_queries/insights/utils/data_warehouse_schema_mixin.py@@ -6,6 +6,17 @@ from posthog.hogql.database.models import DatabaseField, Tablefrom posthog.hogql_queries.insights.query_context import QueryContextProtocol+def resolve_warehouse_field(database: Database, table_name: str, field_name: str) -> DatabaseField:+ table = database.get_table(table_name)+ field = table.fields.get(field_name)+ if field is None:+ raise ValidationError(detail=f"Unknown field {table_name}.{field_name}")+ if isinstance(field, Table):+ raise ValidationError(detail=f"{table_name}.{field_name} points to a table, not a field")+ assert isinstance(field, DatabaseField)+ return field++class DataWarehouseSchemaMixin(QueryContextProtocol):_hogql_database: Database | None = None@@ -21,11 +32,4 @@ class DataWarehouseSchemaMixin(QueryContextProtocol):return self._hogql_databasedef get_warehouse_field(self, table_name: str, field_name: str) -> DatabaseField:- table = self.hogql_database.get_table(table_name)- field = table.fields.get(field_name)- if field is None:- raise ValidationError(detail=f"Unknown field {table_name}.{field_name}")- if isinstance(field, Table):- raise ValidationError(detail=f"{table_name}.{field_name} points to a table, not a field")- assert isinstance(field, DatabaseField)- return field+ return resolve_warehouse_field(self.hogql_database, table_name, field_name)