: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): make group key created_at cutoff timezone-aware (#68279)
Xander06abd69a1148
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 0945c71444bf..657e47d0fe8b 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -1994,7 +1994,12 @@ def _setup_group_key_fields(database: Database, group_types: list[dict[str, Any]raw_field_name = f"_{field_name}_raw"table.fields[raw_field_name] = original_field.model_copy(update={"hidden": True})- created_at_str = group_mapping["created_at"].strftime("%Y-%m-%d %H:%M:%S")+ # Must stay a datetime constant: a naive string literal would be parsed by ClickHouse in the+ # project's timezone (the comparison is against toTimeZone(timestamp, <project tz>)), shifting+ # the cutoff by the project's UTC offset.+ created_at = group_mapping["created_at"]+ if created_at.tzinfo is None:+ created_at = created_at.replace(tzinfo=UTC)table.fields[field_name] = ExpressionField(name=field_name,@@ -2004,7 +2009,7 @@ def _setup_group_key_fields(database: Database, group_types: list[dict[str, Any]ast.CompareOperation(left=ast.Field(chain=["timestamp"]),op=ast.CompareOperationOp.Lt,- right=ast.Constant(value=created_at_str),+ right=ast.Constant(value=created_at),),ast.Constant(value=""),ast.Field(chain=[raw_field_name]),diff --git a/posthog/hogql/test/test_group_filtering.py b/posthog/hogql/test/test_group_filtering.pyindex b3252053c3f5..cc76337c3c4a 100644--- a/posthog/hogql/test/test_group_filtering.py+++ b/posthog/hogql/test/test_group_filtering.py@@ -6,6 +6,8 @@ from datetime import UTC, datetimefrom posthog.test.base import APIBaseTest+from parameterized import parameterized+from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import Databasefrom posthog.hogql.parser import parse_select@@ -32,8 +34,15 @@ class TestGroupKeyFiltering(APIBaseTest):self.database = Database.create_for(team=self.team)self.context = HogQLContext(team=self.team, database=self.database, enable_select_queries=True)- def test_group_field_with_mapping_and_created_at(self):- """Test that $group_0 gets filtering when GroupTypeMapping exists with created_at"""+ # The created_at cutoff must be printed as a timezone-aware constant: a naive string literal is+ # parsed by ClickHouse in the project's timezone, shifting the cutoff by the project's UTC offset.+ @parameterized.expand(+ [+ ("UTC", "toDateTime64('2023-01-15 12:00:00.000000', 6, 'UTC')"),+ ("America/Mexico_City", "toDateTime64('2023-01-15 06:00:00.000000', 6, 'America/Mexico_City')"),+ ]+ )+ def test_group_field_with_mapping_and_created_at(self, timezone: str, expected_cutoff: str):self._create_mapping_and_rebuild(team=self.team,project=self.team.project,@@ -41,6 +50,8 @@ class TestGroupKeyFiltering(APIBaseTest):group_type_index=0,created_at=datetime(2023, 1, 15, 12, 0, 0, tzinfo=UTC),)+ self.team.timezone = timezone+ self.team.save()self._rebuild_database()query = "SELECT $group_0 FROM events"@@ -49,7 +60,7 @@ class TestGroupKeyFiltering(APIBaseTest):sql, _ = prepare_and_print_ast(parsed, context=self.context, dialect="clickhouse")self.assertIn(- "SELECT if(less(toTimeZone(events.timestamp, %(hogql_val_0)s), %(hogql_val_1)s), %(hogql_val_2)s, events.`$group_0`) AS `$group_0` FROM events WHERE equals(events.team_id,",+ f"SELECT if(less(toTimeZone(events.timestamp, %(hogql_val_0)s), {expected_cutoff}), %(hogql_val_1)s, events.`$group_0`) AS `$group_0` FROM events WHERE equals(events.team_id,",sql,)@@ -192,7 +203,7 @@ class TestGroupKeyFiltering(APIBaseTest):sql, _ = prepare_and_print_ast(parsed, context=self.context, dialect="clickhouse")self.assertIn(- "ON equals(if(less(toTimeZone(events.timestamp, %(hogql_val_2)s), %(hogql_val_3)s), %(hogql_val_4)s, events.`$group_0`), events__group_0.key)",+ "ON equals(if(less(toTimeZone(events.timestamp, %(hogql_val_2)s), toDateTime64('2023-01-15 12:00:00.000000', 6, 'UTC')), %(hogql_val_3)s, events.`$group_0`), events__group_0.key)",sql,)@@ -213,4 +224,7 @@ class TestGroupKeyFiltering(APIBaseTest):sql, _ = prepare_and_print_ast(parsed, context=self.context, dialect="clickhouse")self.assertIn("ON equals(if(less(toTimeZone(events.timestamp,", sql)- self.assertIn("), %(hogql_val_3)s), %(hogql_val_4)s, events.`$group_0`), events__group_0.key)", sql)+ self.assertIn(+ "toDateTime64('2023-01-15 12:00:00.000000', 6, 'UTC')), %(hogql_val_3)s, events.`$group_0`), events__group_0.key)",+ sql,+ )diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambrindex 5cfffa054747..1e7f18bb2b27 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambr@@ -146,7 +146,7 @@# name: TestExperimentQueryRunner.test_query_runner_group_aggregation_mean_metric'''WITH exposures AS- (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), '2020-01-01 12:00:00'), '', events.`$group_0`) AS entity_id,+ (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('today', 6, 'UTC')), '', events.`$group_0`) AS entity_id,if(greater(uniqExact(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', '')), 1), '$multiple', any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''))) AS variant,min(toTimeZone(events.timestamp, 'UTC')) AS first_exposure_time,max(toTimeZone(events.timestamp, 'UTC')) AS last_exposure_time,@@ -173,7 +173,7 @@WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))), and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), ifNull(notILike(toString(events__person.properties___email), '%@posthog.com%'), 1), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''), ['control', 'test']))GROUP BY entity_id),metric_events AS- (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), '2020-01-01 12:00:00'), '', events.`$group_0`) AS entity_id,+ (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('today', 6, 'UTC')), '', events.`$group_0`) AS entity_id,toTimeZone(events.timestamp, 'UTC') AS timestamp,coalesce(accurateCastOrNull(1, 'Float64'), 0) AS valueFROM events@@ -211,7 +211,7 @@# name: TestExperimentQueryRunner.test_query_runner_group_aggregation_mean_property_sum_metric'''WITH exposures AS- (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), '2020-01-01 12:00:00'), '', events.`$group_0`) AS entity_id,+ (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('today', 6, 'UTC')), '', events.`$group_0`) AS entity_id,if(greater(uniqExact(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', '')), 1), '$multiple', any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''))) AS variant,min(toTimeZone(events.timestamp, 'UTC')) AS first_exposure_time,max(toTimeZone(events.timestamp, 'UTC')) AS last_exposure_time,@@ -238,7 +238,7 @@WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))), and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), ifNull(notILike(toString(events__person.properties___email), '%@posthog.com%'), 1), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''), ['control', 'test']))GROUP BY entity_id),metric_events AS- (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), '2020-01-01 12:00:00'), '', events.`$group_0`) AS entity_id,+ (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('today', 6, 'UTC')), '', events.`$group_0`) AS entity_id,toTimeZone(events.timestamp, 'UTC') AS timestamp,coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) AS valueFROM events@@ -2700,7 +2700,7 @@# name: TestExperimentQueryRunner.test_query_runner_with_unique_group_metric'''WITH exposures AS- (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), '2020-01-01 12:00:00'), '', events.`$group_0`) AS entity_id,+ (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('today', 6, 'UTC')), '', events.`$group_0`) AS entity_id,if(greater(uniqExact(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', '')), 1), '$multiple', any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''))) AS variant,min(toTimeZone(events.timestamp, 'UTC')) AS first_exposure_time,max(toTimeZone(events.timestamp, 'UTC')) AS last_exposure_time,@@ -2727,7 +2727,7 @@WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC'))), and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), ifNull(notILike(toString(events__person.properties___email), '%@posthog.com%'), 1), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''), ['control', 'test']))GROUP BY entity_id),metric_events AS- (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), '2020-01-01 12:00:00'), '', events.`$group_0`) AS entity_id,+ (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('today', 6, 'UTC')), '', events.`$group_0`) AS entity_id,toTimeZone(events.timestamp, 'UTC') AS timestamp,1 AS valueFROM eventsdiff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_experiment_exposures_query_runner.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_experiment_exposures_query_runner.ambrindex 7f745931a389..944283460fb5 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_experiment_exposures_query_runner.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_experiment_exposures_query_runner.ambr@@ -387,7 +387,7 @@# name: TestExperimentExposuresQueryRunner.test_exposure_query_using_group_aggregation_0_direct'''WITH first_exposures AS- (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), '2024-01-07 12:00:00'), '', events.`$group_0`) AS entity_id,+ (SELECT if(less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('today', 6, 'UTC')), '', events.`$group_0`) AS entity_id,if(greater(uniqExact(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', '')), 1), '$multiple', any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''))) AS variant,toDateOrNull(toString(min(toTimeZone(events.timestamp, 'UTC')))) AS dayFROM events