: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): honor configured id/distinct_id over table columns (#66331)
Thomas Obermüller6e0978329c40
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 8e97ef44d1f6..15f191165ed8 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -1639,7 +1639,11 @@ class Database(BaseModel):if table is None:return root_node- if "id" not in table.fields.keys():+ # The configured `id_field` must win even when the source table has its own column+ # literally named `id`. Without this guard the virtual mapping is skipped and queries+ # silently resolve to the table's own `id` column instead of the configured field.+ id_field_is_remapped = warehouse_modifier.id_field != "id"+ if id_field_is_remapped or "id" not in table.fields.keys():table.fields["id"] = ExpressionField(name="id",expr=parse_expr(warehouse_modifier.id_field),@@ -1678,13 +1682,21 @@ class Database(BaseModel):),)- # TODO: Need to decide how the distinct_id and person_id fields are going to be handled- if "distinct_id" not in table.fields.keys():+ # As with `id` and `timestamp` above, the configured `distinct_id_field` must win over a+ # source column literally named `distinct_id`; otherwise the virtual mapping is skipped and+ # the wrong column is used silently.+ distinct_id_field_is_remapped = warehouse_modifier.distinct_id_field != "distinct_id"+ if distinct_id_field_is_remapped or "distinct_id" not in table.fields.keys():table.fields["distinct_id"] = ExpressionField(name="distinct_id",expr=parse_expr(warehouse_modifier.distinct_id_field),)+ # person_id is deliberately left as "inject only when absent": the modifier has no+ # person_id_field to remap from, and a source column literally named `person_id` is+ # plausibly authoritative (e.g. an already-resolved person UUID), so it should win. When+ # the table has no `person_id`, derive it from the events join if one exists, else fall+ # back to the configured distinct_id_field.if "person_id" not in table.fields.keys():events_join = next((diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex 97103e2b7b3b..e41f41bf76cd 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -1540,6 +1540,132 @@ class TestDatabase(BaseTest, QueryMatchingTest):timestamp_field = db.get_table("native_timestamp_table").fields["timestamp"]assert isinstance(timestamp_field, DateTimeDatabaseField)+ @parameterized.expand(+ [+ ("id", "real_id"),+ ("distinct_id", "real_distinct_id"),+ ]+ )+ def test_data_warehouse_events_modifier_remaps_identity_field_over_existing_column(+ self, virtual_field: str, configured_column: str+ ):+ # A warehouse table can have its own column literally named `id` / `distinct_id` while the+ # series is configured to use a different column. The configured `id_field` / `distinct_id_field`+ # must win, so the virtual field resolves to the configured column rather than the table's own+ # decoy column (which would otherwise be selected silently).+ credentials = DataWarehouseCredential.objects.create(+ access_key="test_key", access_secret="test_secret", team=self.team+ )+ DataWarehouseTable.objects.create(+ name="decoy_identity_table",+ format="Parquet",+ team=self.team,+ credential=credentials,+ url_pattern="s3://test/*",+ columns={+ "real_id": "String",+ "real_distinct_id": "String",+ "id": "String",+ "distinct_id": "String",+ "created_at": "DateTime64(3, 'UTC')",+ },+ )+ modifiers = HogQLQueryModifiers(+ dataWarehouseEventsModifiers=[+ DataWarehouseEventsModifier(+ table_name="decoy_identity_table",+ id_field="real_id",+ distinct_id_field="real_distinct_id",+ timestamp_field="created_at",+ )+ ]+ )++ db = Database.create_for(team=self.team, modifiers=modifiers)++ field = db.get_table("decoy_identity_table").fields[virtual_field]+ assert isinstance(field, ExpressionField)+ assert isinstance(field.expr, ast.Field)+ assert field.expr.chain == [configured_column]++ @parameterized.expand(+ [+ ("id",),+ ("distinct_id",),+ ]+ )+ def test_data_warehouse_events_modifier_keeps_existing_identity_column_when_configured(self, virtual_field: str):+ # When the configured field name equals the virtual field name, the table's own column is 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_identity_table",+ format="Parquet",+ team=self.team,+ credential=credentials,+ url_pattern="s3://test/*",+ columns={+ "id": "String",+ "distinct_id": "String",+ "created_at": "DateTime64(3, 'UTC')",+ },+ )+ modifiers = HogQLQueryModifiers(+ dataWarehouseEventsModifiers=[+ DataWarehouseEventsModifier(+ table_name="native_identity_table",+ id_field="id",+ distinct_id_field="distinct_id",+ timestamp_field="created_at",+ )+ ]+ )++ db = Database.create_for(team=self.team, modifiers=modifiers)++ field = db.get_table("native_identity_table").fields[virtual_field]+ # StringDatabaseField implies the column was not wrapped in a remapping ExpressionField+ assert isinstance(field, StringDatabaseField)++ def test_data_warehouse_events_modifier_keeps_existing_person_id_column(self):+ # Unlike id/distinct_id/timestamp, person_id has no configured field on the modifier to remap+ # from, and a native `person_id` column is treated as authoritative (e.g. an already-resolved+ # person UUID). It must win over the distinct_id-derived fallback rather than being overridden.+ credentials = DataWarehouseCredential.objects.create(+ access_key="test_key", access_secret="test_secret", team=self.team+ )+ DataWarehouseTable.objects.create(+ name="native_person_id_table",+ format="Parquet",+ team=self.team,+ credential=credentials,+ url_pattern="s3://test/*",+ columns={+ "id": "String",+ "user_id": "String",+ "person_id": "String",+ "created_at": "DateTime64(3, 'UTC')",+ },+ )+ modifiers = HogQLQueryModifiers(+ dataWarehouseEventsModifiers=[+ DataWarehouseEventsModifier(+ table_name="native_person_id_table",+ id_field="id",+ distinct_id_field="user_id",+ timestamp_field="created_at",+ )+ ]+ )++ db = Database.create_for(team=self.team, modifiers=modifiers)++ person_id_field = db.get_table("native_person_id_table").fields["person_id"]+ # StringDatabaseField implies the column was not wrapped in a remapping ExpressionField+ assert isinstance(person_id_field, StringDatabaseField)+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_distinct_id.csv b/posthog/hogql_queries/insights/trends/test/data/trends_dw_decoy_distinct_id.csvnew file mode 100644index 000000000000..da3eafc0f896--- /dev/null+++ b/posthog/hogql_queries/insights/trends/test/data/trends_dw_decoy_distinct_id.csv@@ -0,0 +1,3 @@+id,user_id,distinct_id,event_time,prop_1+1,alice,shared,2023-01-01,a+2,bob,shared,2023-01-01,bdiff --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 344f241d997a..7efc1177d4a7 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@@ -41,6 +41,7 @@ from posthog.hogql.timings import HogQLTimingsfrom posthog.hogql_queries.insights.trends.trends_query_builder import TrendsQueryBuilderfrom posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.models.instance_setting import override_instance_configfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable@@ -159,6 +160,57 @@ class TestTrendsDataWarehouseQuery(ClickhouseTestMixin, BaseTest):assert set(response.columns).issubset({"date", "total"})assert response.results[0][1] == [1, 1, 1, 1, 0, 0, 0]+ def setup_data_warehouse_with_decoy_distinct_id(self):+ # Table whose real actor identifier lives in `user_id`, but which also has a column literally+ # named `distinct_id` (a decoy, e.g. a source-system id). With `aggregate_users_by_distinct_id`,+ # trends `dau` counts the virtual `distinct_id` field, which must resolve to the configured+ # `distinct_id_field` (`user_id`) rather than the decoy column, or unique-user counts are wrong.+ table, _source, _credential, _df, self.cleanUpDataWarehouse = create_data_warehouse_table_from_csv(+ csv_path=Path(__file__).parent / "data" / "trends_dw_decoy_distinct_id.csv",+ table_name="test_table_decoy_distinct_id",+ table_columns={+ "id": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "user_id": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "distinct_id": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "event_time": {"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_distinct_id_field(self):+ # Regression: with `aggregate_users_by_distinct_id`, trends `dau` counts the virtual `distinct_id`+ # field, which must resolve to the configured `distinct_id_field` (`user_id`) even when the source+ # table has its own column named `distinct_id`. Both rows on 2023-01-01 share one decoy+ # `distinct_id` value but have two distinct `user_id`s, so counting `user_id` yields 2 while+ # counting the decoy column would yield 1.+ table_name = self.setup_data_warehouse_with_decoy_distinct_id()++ 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="user_id",+ timestamp_field="event_time",+ math="dau",+ )+ ],+ )++ with override_instance_config("AGGREGATE_BY_DISTINCT_IDS_TEAMS", f"{self.team.pk}"), 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] == [2, 0, 0, 0, 0, 0, 0]+@snapshot_clickhouse_queriesdef test_trends_data_warehouse(self):table_name = self.setup_data_warehouse()