: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(data-warehouse): respect configured timestamp_field over existing timestamp column (#63625)
posthog[bot]d528d3878d1d
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 99ba4315e802..8e97ef44d1f6 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -1647,8 +1647,12 @@ class Database(BaseModel):table_has_no_timestamp_field = "timestamp" not in table.fields.keys()timestamp_field_is_datetime = isinstance(table.fields.get("timestamp"), DateTimeDatabaseField)+ # The configured timestamp_field must win even when the source table has its own DateTime+ # column literally named `timestamp` (e.g. an ingestion timestamp). Without this, the virtual+ # mapping is skipped and queries silently bucket/filter on the wrong column.+ timestamp_field_is_remapped = warehouse_modifier.timestamp_field != "timestamp"- if table_has_no_timestamp_field or not timestamp_field_is_datetime:+ if timestamp_field_is_remapped or table_has_no_timestamp_field or not timestamp_field_is_datetime:# get_table raises (rather than skipping) when no backing row exists — see resolvers below.table_model = get_table(warehouse_modifier)timestamp_field_type = table_model.get_clickhouse_column_type(warehouse_modifier.timestamp_field)diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex 947554ac0c55..97103e2b7b3b 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -22,6 +22,7 @@ from posthog.schema import (PersonsOnEventsMode,)+from posthog.hogql import astfrom posthog.hogql.constants import MAX_SELECT_RETURNED_ROWSfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import (@@ -40,6 +41,7 @@ from posthog.hogql.database.lazy_join_tags import FOREIGN_KEYfrom posthog.hogql.database.models import (DANGEROUS_NoTeamIdCheckTable,DatabaseField,+ DateTimeDatabaseField,ExpressionField,FieldTraverser,LazyJoin,@@ -1470,6 +1472,74 @@ class TestDatabase(BaseTest, QueryMatchingTest):prepare_and_print_ast(parse_select("SELECT person_id FROM warehouse_table"), context, dialect="clickhouse")+ def test_data_warehouse_events_modifier_remaps_timestamp_over_existing_column(self):+ # A warehouse table can have its own DateTime column literally named `timestamp` (e.g. an+ # ingestion timestamp) while the series is configured to use a different event-time column.+ # The configured timestamp_field must win: `timestamp` should resolve to the configured column,+ # not the table's own `timestamp`, so queries don't silently bucket/filter on the wrong column.+ credentials = DataWarehouseCredential.objects.create(+ access_key="test_key", access_secret="test_secret", team=self.team+ )+ DataWarehouseTable.objects.create(+ name="decoy_table",+ format="Parquet",+ team=self.team,+ credential=credentials,+ url_pattern="s3://test/*",+ columns={+ "id": "String",+ "event_time": "DateTime64(3, 'UTC')",+ "timestamp": "DateTime64(3, 'UTC')",+ },+ )+ modifiers = HogQLQueryModifiers(+ dataWarehouseEventsModifiers=[+ DataWarehouseEventsModifier(+ table_name="decoy_table",+ id_field="id",+ timestamp_field="event_time",+ distinct_id_field="id",+ )+ ]+ )++ db = Database.create_for(team=self.team, modifiers=modifiers)++ timestamp_field = db.get_table("decoy_table").fields["timestamp"]+ assert isinstance(timestamp_field, ExpressionField)+ assert isinstance(timestamp_field.expr, ast.Field)+ assert timestamp_field.expr.chain == ["event_time"]++ def test_data_warehouse_events_modifier_keeps_existing_timestamp_column_when_configured(self):+ # When the configured timestamp_field is `timestamp` itself, the table's own DateTime column+ # should be used directly rather than wrapped in a remapping expression.+ credentials = DataWarehouseCredential.objects.create(+ access_key="test_key", access_secret="test_secret", team=self.team+ )+ DataWarehouseTable.objects.create(+ name="native_timestamp_table",+ format="Parquet",+ team=self.team,+ credential=credentials,+ url_pattern="s3://test/*",+ columns={"id": "String", "timestamp": "DateTime64(3, 'UTC')"},+ )+ modifiers = HogQLQueryModifiers(+ dataWarehouseEventsModifiers=[+ DataWarehouseEventsModifier(+ table_name="native_timestamp_table",+ id_field="id",+ timestamp_field="timestamp",+ distinct_id_field="id",+ )+ ]+ )++ db = Database.create_for(team=self.team, modifiers=modifiers)++ timestamp_field = db.get_table("native_timestamp_table").fields["timestamp"]+ assert isinstance(timestamp_field, DateTimeDatabaseField)+def test_data_warehouse_events_modifiers_with_dot_notation(self):credentials = DataWarehouseCredential.objects.create(access_key="test_key", access_secret="test_secret", team=self.teamdiff --git a/posthog/hogql_queries/insights/trends/test/data/trends_dw_decoy_timestamp.csv b/posthog/hogql_queries/insights/trends/test/data/trends_dw_decoy_timestamp.csvnew file mode 100644index 000000000000..b175ce60b185--- /dev/null+++ b/posthog/hogql_queries/insights/trends/test/data/trends_dw_decoy_timestamp.csv@@ -0,0 +1,5 @@+id,event_time,timestamp,prop_1+1,2023-01-01,2023-01-04,a+2,2023-01-02,2023-01-04,b+3,2023-01-03,2023-01-04,c+4,2023-01-04,2023-01-04,ddiff --git a/posthog/hogql_queries/insights/trends/test/test_trends_data_warehouse_query.py b/posthog/hogql_queries/insights/trends/test/test_trends_data_warehouse_query.pyindex d3e07cdd1beb..344f241d997a 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends_data_warehouse_query.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends_data_warehouse_query.py@@ -112,6 +112,53 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):return table.name+ def setup_data_warehouse_with_decoy_timestamp(self):+ # Table whose real event time lives in `event_time`, but which also has a DateTime column+ # literally named `timestamp` (e.g. an ingestion timestamp). The DataWarehouseEventsModifier+ # must still map the configured `timestamp_field` so queries don't bucket on the wrong column.+ table, _source, _credential, _df, self.cleanUpDataWarehouse = create_data_warehouse_table_from_csv(+ csv_path=Path(__file__).parent / "data" / "trends_dw_decoy_timestamp.csv",+ table_name="test_table_decoy",+ table_columns={+ "id": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "event_time": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "timestamp": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "prop_1": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ },+ test_bucket=TEST_BUCKET,+ team=self.team,+ )++ return table.name++ def test_trends_data_warehouse_uses_configured_timestamp_field(self):+ # Regression: the configured `timestamp_field` must drive bucketing even when the source table+ # has its own DateTime column named `timestamp`. Each row has a distinct `event_time` day, so+ # bucketing by `event_time` spreads counts across days ([1, 1, 1, 1, 0, 0, 0]); bucketing by the+ # decoy `timestamp` (all 2023-01-04) would pile everything onto day 4 ([0, 0, 0, 4, 0, 0, 0]).+ table_name = self.setup_data_warehouse_with_decoy_timestamp()++ trends_query = TrendsQuery(+ kind="TrendsQuery",+ dateRange=DateRange(date_from="2023-01-01"),+ series=[+ DataWarehouseNode(+ id=table_name,+ table_name=table_name,+ id_field="id",+ distinct_id_field="id",+ timestamp_field="event_time",+ )+ ],+ )++ with freeze_time("2023-01-07"):+ response = self.get_response(trends_query=trends_query)++ assert response.columns is not None+ assert set(response.columns).issubset({"date", "total"})+ assert response.results[0][1] == [1, 1, 1, 1, 0, 0, 0]+@snapshot_clickhouse_queriesdef test_trends_data_warehouse(self):table_name = self.setup_data_warehouse()diff --git a/products/product_analytics/backend/hogql_queries/stickiness/test/data/stickiness_dw_decoy_timestamp.csv b/products/product_analytics/backend/hogql_queries/stickiness/test/data/stickiness_dw_decoy_timestamp.csvnew file mode 100644index 000000000000..9f63fad9adfa--- /dev/null+++ b/products/product_analytics/backend/hogql_queries/stickiness/test/data/stickiness_dw_decoy_timestamp.csv@@ -0,0 +1,5 @@+id,event_time,timestamp,prop_1+u1,2023-01-01,2023-01-04,a+u1,2023-01-02,2023-01-04,a+u1,2023-01-03,2023-01-04,a+u2,2023-01-05,2023-01-04,bdiff --git a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.pyindex ad04b84f9e88..785b58c10ab8 100644--- a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py+++ b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py@@ -179,6 +179,26 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):return table.name+ def _setup_data_warehouse_with_decoy_timestamp(self) -> str:+ # Table whose real event time lives in `event_time`, but which also has a DateTime column+ # literally named `timestamp` (e.g. an ingestion timestamp). The DataWarehouseEventsModifier+ # skips injecting a virtual `timestamp` field in this case, so a runner that hardcodes+ # `e.timestamp` would silently bucket/filter on the wrong column.+ table, _source, _credential, _df, self.cleanUpDataWarehouse = create_data_warehouse_table_from_csv(+ csv_path=Path(__file__).parent / "data" / "stickiness_dw_decoy_timestamp.csv",+ table_name="test_table_stickiness_decoy",+ table_columns={+ "id": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "event_time": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "timestamp": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "prop_1": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ },+ test_bucket=TEST_BUCKET,+ team=self.team,+ )++ return table.name+def _create_test_events(self):self._create_events([@@ -348,6 +368,34 @@ class TestStickinessQueryRunner(ClickhouseTestMixin, APIBaseTest):assert response.results[0]["data"] == [1, 0, 0, 0, 0, 0, 0]assert response.results[0]["days"] == [1, 2, 3, 4, 5, 6, 7]+ def test_stickiness_data_warehouse_uses_configured_timestamp_field(self):+ # Regression: the configured `timestamp_field` must drive interval bucketing even when the+ # source table has its own DateTime column named `timestamp`. u1 has activity on 3 distinct+ # `event_time` days and u2 on 1, so bucketing by `event_time` yields one actor in 1 interval+ # and one actor in 3. Bucketing by the decoy `timestamp` (all 2023-01-04) would instead put+ # both actors in a single interval -> [2, 0, 0, 0, 0, 0, 0].+ table_name = self._setup_data_warehouse_with_decoy_timestamp()++ with freeze_time("2023-01-07"):+ response = self._run_query(+ series=[+ DataWarehouseNode(+ id=table_name,+ table_name=table_name,+ id_field="id",+ distinct_id_field="id",+ timestamp_field="event_time",+ )+ ],+ date_from="2023-01-01",+ date_to="2023-01-07",+ )++ assert isinstance(response, StickinessQueryResponse)+ assert response.results[0]["label"] == table_name+ assert response.results[0]["data"] == [1, 0, 1, 0, 0, 0, 0]+ assert response.results[0]["days"] == [1, 2, 3, 4, 5, 6, 7]+def test_days(self):self._create_test_events()