Skip to content

: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.

fix(hogql): person display name falls through empty-string props (#62734)

Xander4de9ecb922dd
diff --git a/frontend/src/queries/nodes/DataTable/exportTransformers.ts b/frontend/src/queries/nodes/DataTable/exportTransformers.ts
index 705f2af344eb..409b511d6913 100644
--- a/frontend/src/queries/nodes/DataTable/exportTransformers.ts
+++ b/frontend/src/queries/nodes/DataTable/exportTransformers.ts
@@ -9,7 +9,7 @@ const PERSON_COLUMN = 'person'
* Replaces the person column with a coalesce expression using personDisplayNameProperties for performance reasons
*/
export function transformColumnsForExport(columns: string[], personDisplayNameProperties: string[]): string[] {
- const props = personDisplayNameProperties.map((key) => `toString(person.properties.${key})`)
+ const props = personDisplayNameProperties.map((key) => `nullIf(toString(person.properties.${key}), '')`)
const expr = `coalesce(${[...props, 'distinct_id'].join(', ')})`
return columns.map((column) => {
const cleanColumn = removeExpressionComment(column)
diff --git a/posthog/hogql_queries/actors_query_runner.py b/posthog/hogql_queries/actors_query_runner.py
index 6cbaecd9f1fa..ff10fcf52a94 100644
--- a/posthog/hogql_queries/actors_query_runner.py
+++ b/posthog/hogql_queries/actors_query_runner.py
@@ -1,4 +1,3 @@
-import re
import itertools
from collections.abc import Iterable, Iterator, Sequence
from typing import TYPE_CHECKING, Any, Optional
@@ -32,6 +31,7 @@ from posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQ
from posthog.hogql_queries.insights.insight_actors_query_runner import InsightActorsQueryRunner
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode, QueryRunner, get_query_runner
+from posthog.hogql_queries.utils.person_display_name import person_display_name_property_exprs
from posthog.models import User
@@ -559,13 +559,7 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):
def _get_person_display_name_column(self) -> ast.Expr:
property_keys = self.team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
- # Only use backticks for property names with spaces or special chars
- props = []
- for key in property_keys:
- if re.match(r"^[A-Za-z_$][A-Za-z0-9_$]*$", key):
- props.append(f"toString(properties.{key})")
- else:
- props.append(f"toString(properties.`{key}`)")
+ props = person_display_name_property_exprs(property_keys, "properties")
# nosemgrep: hogql-fstring-audit (property_keys from team config is admin-only, not user input)
return parse_expr(f"(coalesce({', '.join([*props, 'toString(id)'])}), toString(id))")
diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.py
index 0bb871a3f19c..f73dc0a99538 100644
--- a/posthog/hogql_queries/events_query_runner.py
+++ b/posthog/hogql_queries/events_query_runner.py
@@ -28,6 +28,7 @@ from posthog.clickhouse.query_tagging import tag_contains_user_hogql
from posthog.hogql_queries.insights.insight_actors_query_runner import InsightActorsQueryRunner
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, get_query_runner
+from posthog.hogql_queries.utils.person_display_name import person_display_name_property_exprs
from posthog.models import Person, PropertyDefinition
from posthog.models.element import chain_to_elements
from posthog.models.person.person import get_distinct_ids_for_subquery
@@ -97,13 +98,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
person_indices.append(index)
elif col.split("--")[0].strip() == "person_display_name":
property_keys = self.team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
- # Only use backticks for property names with spaces or special chars
- props = []
- for key in property_keys:
- if re.match(r"^[A-Za-z_$][A-Za-z0-9_$]*$", key):
- props.append(f"toString(person.properties.{key})")
- else:
- props.append(f"toString(person.properties.`{key}`)")
+ props = person_display_name_property_exprs(property_keys, "person.properties")
expr = f"(coalesce({', '.join([*props, 'distinct_id'])}), toString(person.id), distinct_id)"
select_input.append(expr)
else:
@@ -337,12 +332,7 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
property_keys = (
self.team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
)
- props = []
- for key in property_keys:
- if re.match(r"^[A-Za-z_$][A-Za-z0-9_$]*$", key):
- props.append(f"toString(person.properties.{key})")
- else:
- props.append(f"toString(person.properties.`{key}`)")
+ props = person_display_name_property_exprs(property_keys, "person.properties")
expr = f"(coalesce({', '.join([*props, 'distinct_id'])}), toString(person.id))"
newCol = re.sub(r"person_display_name -- Person ", expr, col)
columns.append(newCol)
diff --git a/posthog/hogql_queries/sessions_query_runner.py b/posthog/hogql_queries/sessions_query_runner.py
index 665b3e17b110..7aaa1b201b61 100644
--- a/posthog/hogql_queries/sessions_query_runner.py
+++ b/posthog/hogql_queries/sessions_query_runner.py
@@ -21,6 +21,7 @@ from posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
from posthog.clickhouse.query_tagging import tag_contains_user_hogql
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+from posthog.hogql_queries.utils.person_display_name import person_display_name_property_exprs
from posthog.models import Person
from posthog.models.person.person import get_distinct_ids_for_subquery
from posthog.models.person.util import get_person_by_pk_or_uuid
@@ -30,7 +31,6 @@ from posthog.utils import relative_date_parse
from products.actions.backend.models.action import Action
COLUMN_COMMENT_SEPARATOR = " -- "
-VALID_IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z_$][A-Za-z0-9_$]*$")
SUPPORTED_PERSON_PROPERTY_OPERATORS = frozenset(
{
"exact",
@@ -97,14 +97,7 @@ class SessionsQueryRunner(AnalyticsQueryRunner[SessionsQueryResponse]):
def _build_person_display_name_expr(self) -> str:
"""Build the HogQL expression for person_display_name using a subquery join."""
property_keys = self.team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
- # Build coalesce expression for person properties
- props = []
- for key in property_keys:
- if VALID_IDENTIFIER_PATTERN.match(key):
- props.append(f"toString(__person_lookup.properties.{key})")
- else:
- props.append(f"toString(__person_lookup.properties.`{key}`)")
-
+ props = person_display_name_property_exprs(property_keys, "__person_lookup.properties")
# Create a tuple with (display_name, person_id, distinct_id)
# Use sessions.distinct_id to avoid ambiguity with pdi.distinct_id
coalesce_expr = f"coalesce({', '.join([*props, 'sessions.distinct_id'])})"
@@ -534,12 +527,7 @@ class SessionsQueryRunner(AnalyticsQueryRunner[SessionsQueryResponse]):
property_keys = (
self.team.person_display_name_properties or PERSON_DEFAULT_DISPLAY_NAME_PROPERTIES
)
- props = []
- for key in property_keys:
- if VALID_IDENTIFIER_PATTERN.match(key):
- props.append(f"toString(__person_lookup.properties.{key})")
- else:
- props.append(f"toString(__person_lookup.properties.`{key}`)")
+ props = person_display_name_property_exprs(property_keys, "__person_lookup.properties")
expr = f"(coalesce({', '.join([*props, 'sessions.distinct_id'])}), toString(__person_lookup.id))"
new_col = re.sub(r"person_display_name -- Person\s*", expr, col)
order_columns.append(new_col)
diff --git a/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr b/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr
index 59d8f91490d6..b3d6e8406d3e 100644
--- a/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr
+++ b/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr
@@ -2,7 +2,7 @@
# name: TestSessionsQueryRunner.test_anonymous_session_identified_later
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id),
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id),
__person_lookup.properties___email AS email
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
@@ -51,7 +51,7 @@
# name: TestSessionsQueryRunner.test_anonymous_session_not_identified
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
@@ -543,7 +543,7 @@
# name: TestSessionsQueryRunner.test_orderby_person_display_name
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
@@ -572,7 +572,7 @@
GROUP BY person.id
HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)
WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))
- ORDER BY tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id)) DESC
+ ORDER BY tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id)) DESC
LIMIT 101
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -591,7 +591,7 @@
# name: TestSessionsQueryRunner.test_person_display_name_combined_with_other_columns
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id),
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id),
sessions.`$session_duration` AS `$session_duration`
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
@@ -641,7 +641,7 @@
# name: TestSessionsQueryRunner.test_person_display_name_fallback_to_distinct_id
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.properties___nonexistent_property), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___nonexistent_property), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
@@ -687,7 +687,7 @@
# name: TestSessionsQueryRunner.test_person_display_name_field
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
@@ -735,7 +735,7 @@
# name: TestSessionsQueryRunner.test_person_display_name_multiple_persons
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
@@ -764,7 +764,7 @@
GROUP BY person.id
HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __person_lookup ON equals(__pdi.person_id, __person_lookup.id)
WHERE and(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 14:00:05.000000', 6, 'UTC')), greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'UTC')))
- ORDER BY tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id)) ASC
+ ORDER BY tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id)) ASC
LIMIT 101
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -783,7 +783,7 @@
# name: TestSessionsQueryRunner.test_person_display_name_with_custom_properties
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.properties___name), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___name), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
@@ -829,7 +829,7 @@
# name: TestSessionsQueryRunner.test_person_display_name_with_spaces_in_property_name
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.`properties___Property With Spaces`), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
+ tuple(coalesce(nullIf(toString(__person_lookup.`properties___Property With Spaces`), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
@@ -875,7 +875,7 @@
# name: TestSessionsQueryRunner.test_person_display_name_with_star_select
'''
SELECT tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) AS `tuple(sessions.session_id, sessions.distinct_id, sessions.$start_timestamp, sessions.$end_timestamp, sessions.$session_duration, sessions.$entry_current_url, sessions.$end_current_url, sessions.$pageview_count, sessions.$autocapture_count, sessions.$screen_count, sessions.$is_bounce)`,
- tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id)
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
@@ -961,7 +961,7 @@
# name: TestSessionsQueryRunner.test_person_property_combined_with_display_name
'''
SELECT sessions.session_id AS session_id,
- tuple(coalesce(toString(__person_lookup.properties___email), toString(__person_lookup.properties___name), toString(__person_lookup.properties___username), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id),
+ tuple(coalesce(nullIf(toString(__person_lookup.properties___email), ''), nullIf(toString(__person_lookup.properties___name), ''), nullIf(toString(__person_lookup.properties___username), ''), sessions.distinct_id), toString(__person_lookup.id), sessions.distinct_id),
__person_lookup.properties___name AS name
FROM
(SELECT nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
diff --git a/posthog/hogql_queries/test/test_actors_query_runner.py b/posthog/hogql_queries/test/test_actors_query_runner.py
index 5fb183401f42..ea1a235cef2d 100644
--- a/posthog/hogql_queries/test/test_actors_query_runner.py
+++ b/posthog/hogql_queries/test/test_actors_query_runner.py
@@ -8,6 +8,7 @@ from unittest.mock import patch
from django.test import override_settings
+from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from posthog.schema import (
@@ -766,6 +767,57 @@ class TestActorsQueryRunner(ClickhouseTestMixin, APIBaseTest):
display_names = [row[0]["display_name"] for row in response.results]
assert set(display_names) == {"Test User With Spaces"}
+ @parameterized.expand(
+ [
+ (
+ "empty_first_prop_falls_through",
+ ["name", "email"],
+ {"name": "", "email": "[email protected]"},
+ ),
+ (
+ "non_empty_value_still_wins",
+ ["name", "email"],
+ {"name": "Test User", "email": "[email protected]"},
+ "Test User",
+ ),
+ ]
+ )
+ def test_person_display_name_empty_string_fallthrough(
+ self, _name, display_name_properties, person_properties, expected_display_name
+ ):
+ # An empty-string property should fall through to the next configured property.
+ _create_person(
+ team_id=self.team.pk,
+ distinct_ids=["id_email", "id_anon"],
+ properties=person_properties,
+ )
+ self.team.person_display_name_properties = display_name_properties
+ self.team.save()
+ self.team.refresh_from_db()
+ flush_persons_and_events()
+ query = ActorsQuery(select=["person_display_name"])
+ runner = self._create_runner(query)
+ response = runner.calculate()
+ display_names = [row[0]["display_name"] for row in response.results]
+ assert set(display_names) == {expected_display_name}
+
+ def test_person_display_name_all_empty_strings_falls_back_to_id(self):
+ person = _create_person(
+ team_id=self.team.pk,
+ distinct_ids=["id_email", "id_anon"],
+ properties={"name": "", "email": ""},
+ )
+ self.team.person_display_name_properties = ["name", "email"]
+ self.team.save()
+ self.team.refresh_from_db()
+ flush_persons_and_events()
+ query = ActorsQuery(select=["person_display_name"])
+ runner = self._create_runner(query)
+ response = runner.calculate()
+ display_names = [row[0]["display_name"] for row in response.results]
+ assert set(display_names) == {str(person.uuid)}
+
def test_select_property_name_with_spaces(self):
_create_person(
team_id=self.team.pk,
diff --git a/posthog/hogql_queries/test/test_events_query_runner.py b/posthog/hogql_queries/test/test_events_query_runner.py
index 8ca8bed571fb..3d3969dfb524 100644
--- a/posthog/hogql_queries/test/test_events_query_runner.py
+++ b/posthog/hogql_queries/test/test_events_query_runner.py
@@ -12,6 +12,8 @@ from posthog.test.base import (
snapshot_clickhouse_queries,
)
+from parameterized import parameterized
+
from posthog.schema import (
CachedEventsQueryResponse,
EventMetadataPropertyFilter,
@@ -719,6 +721,55 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
display_names = [row[1]["display_name"] for row in response.results]
assert set(display_names) == {"id_email", "id_anon"}
+ @parameterized.expand(
+ [
+ (
+ "empty_first_prop_falls_through",
+ ["name", "email"],
+ {"name": "", "email": "[email protected]"},
+ ),
+ ("all_props_empty_falls_back_to_distinct_id", ["name", "email"], {"name": "", "email": ""}, "id_email"),
+ (
+ "non_empty_value_still_wins",
+ ["name", "email"],
+ {"name": "Test User", "email": "[email protected]"},
+ "Test User",
+ ),
+ ]
+ )
+ def test_person_display_name_field_empty_string_fallthrough(
+ self, _name, display_name_properties, person_properties, expected_display_name
+ ):
+ # An empty-string property should fall through to the next configured property,
+ # the same way a missing property does.
+ _create_person(
+ team_id=self.team.pk,
+ distinct_ids=["id_email"],
+ properties=person_properties,
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="id_email",
+ properties={},
+ )
+ flush_persons_and_events()
+
+ self.team.person_display_name_properties = display_name_properties
+ self.team.save()
+ self.team.refresh_from_db()
+ query = EventsQuery(
+ kind="EventsQuery",
+ select=["event", "person_display_name -- Person"],
+ orderBy=["timestamp ASC"],
+ )
+ runner = EventsQueryRunner(query=query, team=self.team)
+ response = runner.run()
+ assert isinstance(response, CachedEventsQueryResponse)
+ display_names = [row[1]["display_name"] for row in response.results]
+ assert set(display_names) == {expected_display_name}
+
def test_person_display_name_field_with_spaces_in_property_name(self):
_create_person(
team_id=self.team.pk,
diff --git a/posthog/hogql_queries/test/test_sessions_query_runner.py b/posthog/hogql_queries/test/test_sessions_query_runner.py
index 1815c725df0e..f7f6ba2a4b28 100644
--- a/posthog/hogql_queries/test/test_sessions_query_runner.py
+++ b/posthog/hogql_queries/test/test_sessions_query_runner.py
@@ -406,6 +406,61 @@ class TestSessionsQueryRunner(ClickhouseTestMixin, APIBaseTest):
# Should fall back to distinct_id
assert person_display["display_name"] == "user1"
+ @parameterized.expand(
+ [
+ (
+ "empty_first_prop_falls_through",
+ ["name", "email"],
+ {"name": "", "email": "[email protected]"},
+ ),
+ ("all_props_empty_falls_back_to_distinct_id", ["name", "email"], {"name": "", "email": ""}, "user1"),
+ (
+ "non_empty_value_still_wins",
+ ["name", "email"],
+ {"name": "Person user1", "email": "[email protected]"},
+ "Person user1",
+ ),
+ ]
+ )
+ def test_person_display_name_empty_string_fallthrough(
+ self, _name, display_name_properties, person_properties, expected_display_name
+ ):
+ """An empty-string property should fall through to the next configured property."""
+ timestamp = "2024-01-01T12:00:00Z"
+ session_id = str(uuid7(timestamp))
+ with freeze_time(timestamp):
+ _create_person(
+ team_id=self.team.pk,
+ distinct_ids=["user1"],
+ properties=person_properties,
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="user1",
+ timestamp=timestamp,
+ properties={"$session_id": session_id},
+ )
+ flush_persons_and_events()
+
+ self.team.person_display_name_properties = display_name_properties
+ self.team.save()
+ self.team.refresh_from_db()
+
+ with freeze_time("2024-01-01T14:00:00Z"):
+ query = SessionsQuery(
+ after="2024-01-01",
+ kind="SessionsQuery",
+ select=["session_id", "person_display_name -- Person"],
+ )
+ runner = SessionsQueryRunner(query=query, team=self.team)
+ response = runner.run()
+
+ assert isinstance(response, CachedSessionsQueryResponse)
+ assert len(response.results) == 1
+ assert response.results[0][1]["display_name"] == expected_display_name
+
@snapshot_clickhouse_queries
def test_person_display_name_with_spaces_in_property_name(self):
"""Test person_display_name handles property names with spaces."""
diff --git a/posthog/hogql_queries/utils/person_display_name.py b/posthog/hogql_queries/utils/person_display_name.py
new file mode 100644
index 000000000000..4f375d59c565
--- /dev/null
+++ b/posthog/hogql_queries/utils/person_display_name.py
@@ -0,0 +1,22 @@
+import re
+
+VALID_IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z_$][A-Za-z0-9_$]*$")
+
+
+def person_display_name_property_exprs(property_keys: list[str], prefix: str) -> list[str]:
+ """Build per-property HogQL expressions for a person display-name coalesce.
+
+ Each property access is wrapped in nullIf(toString(...), '') so empty-string property
+ values become NULL and coalesce falls through to the next property, matching the
+ Python/JS truthiness behavior (only "" is falsy).
+
+ `prefix` is the trusted table/column prefix, e.g. "person.properties", "properties",
+ or "__person_lookup.properties". property_keys come from admin-only team config.
+ """
+ exprs: list[str] = []
+ for key in property_keys:
+ if VALID_IDENTIFIER_PATTERN.match(key):
+ exprs.append(f"nullIf(toString({prefix}.{key}), '')")
+ else:
+ exprs.append(f"nullIf(toString({prefix}.`{key}`), '')")
+ return exprs