: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
feat(customer-analytics): add account custom_properties HogQL join (#66444)
Arthur Moreira de Deus24a587fbec57
diff --git a/posthog/hogql/database/lazy_join_registry.py b/posthog/hogql/database/lazy_join_registry.pyindex 01a779a9d6db..e874a3caa6f7 100644--- a/posthog/hogql/database/lazy_join_registry.py+++ b/posthog/hogql/database/lazy_join_registry.py@@ -2,7 +2,11 @@ from collections.abc import Callablefrom typing import TYPE_CHECKINGfrom posthog.hogql.database import lazy_join_tags as tags-from posthog.hogql.database.schema.account_aggregates import account_notebooks_join, account_tags_join+from posthog.hogql.database.schema.account_aggregates import (+ account_custom_properties_join,+ account_notebooks_join,+ account_tags_join,+)from posthog.hogql.database.schema.error_tracking_fingerprint_issue_state import (join_with_error_tracking_fingerprint_issue_state_table,)@@ -71,6 +75,7 @@ RESOLVERS: dict[str, LazyJoinResolver] = {tags.ERROR_TRACKING_FINGERPRINT_ISSUE_STATE: join_with_error_tracking_fingerprint_issue_state_table,tags.ACCOUNT_TAGS: account_tags_join,tags.ACCOUNT_NOTEBOOKS: account_notebooks_join,+ tags.ACCOUNT_CUSTOM_PROPERTIES: account_custom_properties_join,}diff --git a/posthog/hogql/database/lazy_join_tags.py b/posthog/hogql/database/lazy_join_tags.pyindex b76d6c608d64..3ce9f71e473a 100644--- a/posthog/hogql/database/lazy_join_tags.py+++ b/posthog/hogql/database/lazy_join_tags.py@@ -25,3 +25,4 @@ ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES = "error_tracking_issue_fingerprint_oERROR_TRACKING_FINGERPRINT_ISSUE_STATE = "error_tracking_fingerprint_issue_state"ACCOUNT_TAGS = "account_tags"ACCOUNT_NOTEBOOKS = "account_notebooks"+ACCOUNT_CUSTOM_PROPERTIES = "account_custom_properties"diff --git a/posthog/hogql/database/schema/account_aggregates.py b/posthog/hogql/database/schema/account_aggregates.pyindex d02eed2882f7..42653feff1e7 100644--- a/posthog/hogql/database/schema/account_aggregates.py+++ b/posthog/hogql/database/schema/account_aggregates.py@@ -10,10 +10,13 @@ join subqueries below can be resolved by the planner.from posthog.hogql import astfrom posthog.hogql.base import Exprfrom posthog.hogql.context import HogQLContext-from posthog.hogql.database.lazy_join_tags import ACCOUNT_NOTEBOOKS, ACCOUNT_TAGS+from posthog.hogql.database.lazy_join_tags import ACCOUNT_CUSTOM_PROPERTIES, ACCOUNT_NOTEBOOKS, ACCOUNT_TAGSfrom posthog.hogql.database.models import (+ BooleanDatabaseField,DANGEROUS_NoTeamIdCheckTable,+ DateTimeDatabaseField,FieldOrTable,+ FloatDatabaseField,IntegerDatabaseField,LazyJoin,LazyJoinToAdd,@@ -21,6 +24,7 @@ from posthog.hogql.database.models import (LazyTableToAdd,StringArrayDatabaseField,StringDatabaseField,+ StringJSONDatabaseField,UUIDDatabaseField,)from posthog.hogql.database.postgres_table import PostgresTable@@ -72,6 +76,35 @@ _account_resource_notebooks: _AccountScopedPostgresTable = _AccountScopedPostgre)+_account_custom_property_values: _AccountScopedPostgresTable = _AccountScopedPostgresTable(+ name="_account_custom_property_values",+ postgres_table_name="customer_analytics_custompropertyvalue",+ description="Internal federated table (PostgreSQL `customer_analytics_custompropertyvalue`) of custom property values per account; not for direct querying — use `system.accounts.custom_properties`.",+ fields={+ "id": UUIDDatabaseField(name="id", description="Primary key of the custom property value row."),+ "definition_id": UUIDDatabaseField(+ name="definition_id", description="Custom property definition this value is for."+ ),+ "account_id": UUIDDatabaseField(+ name="account_id", nullable=True, description="Account the value belongs to; join to `system.accounts.id`."+ ),+ "is_deleted": BooleanDatabaseField(+ name="is_deleted", description="Whether this value has been superseded (soft-deleted)."+ ),+ "value_str": StringDatabaseField(name="value_str", nullable=True, description="String value, if a text type."),+ "value_bool": BooleanDatabaseField(+ name="value_bool", nullable=True, description="Boolean value, if a boolean type."+ ),+ "value_num": FloatDatabaseField(+ name="value_num", nullable=True, description="Numeric value, if a numeric type."+ ),+ "value_datetime": DateTimeDatabaseField(+ name="value_datetime", nullable=True, description="Datetime value, if a date/datetime type."+ ),+ },+)++def _account_tags_select() -> ast.SelectQuery | ast.SelectSetQuery:return parse_select("""@@ -97,6 +130,50 @@ def _account_notebooks_select() -> ast.SelectQuery | ast.SelectSetQuery:)+# A custom property value is stored across four typed columns (exactly one non-null per row);+# coalesce them to a single string so any display type round-trips through one column.+_COALESCED_VALUE = (+ "coalesce(cpv.value_str, toString(cpv.value_num), toString(cpv.value_bool), toString(cpv.value_datetime))"+)+++def _account_custom_properties_select(fields_accessed: dict[str, list[str | int]]) -> ast.SelectQuery:+ r"""Aggregate each account's active custom property values.++ `values` is a JSON object keyed by definition id. Accessing a single key+ (`accounts.custom_properties.values.\`<id>\``) is requested as a nested field `values___<id>`;+ a lazy-join subquery can't JSON-extract that after the fact, so each requested key is+ materialized here as its own column via `anyIf` filtered to that definition.+ """+ select: list[ast.Expr] = [parse_expr("cpv.account_id AS account_id")]+ for name, chain in fields_accessed.items():+ if chain == ["account_id"]:+ continue+ if len(chain) >= 2 and chain[0] == "values":+ select.append(+ ast.Alias(+ alias=name,+ expr=parse_expr(+ f"anyIf({_COALESCED_VALUE}, toString(cpv.definition_id) = {{key}})",+ placeholders={"key": ast.Constant(value=str(chain[1]))},+ ),+ )+ )+ elif chain == ["values"]:+ select.append(+ # nosemgrep: hogql-fstring-audit - only interpolates the module-level _COALESCED_VALUE constant (no user input)+ parse_expr(+ f"toJSONString(mapFromArrays(groupArray(toString(cpv.definition_id)), groupArray({_COALESCED_VALUE}))) AS values"+ )+ )+ return ast.SelectQuery(+ select=select,+ select_from=ast.JoinExpr(table=ast.Field(chain=["system", "_account_custom_property_values"]), alias="cpv"),+ where=parse_expr("NOT cpv.is_deleted"),+ group_by=[ast.Field(chain=["cpv", "account_id"])],+ )++class _AccountTagsTable(LazyTable):description: str = ("Internal aggregating table backing `system.accounts.tags`: the distinct, sorted tag names per account."@@ -145,6 +222,33 @@ class _AccountNotebooksTable(LazyTable):return "account_notebooks"+class _AccountCustomPropertiesTable(LazyTable):+ description: str = (+ "Internal aggregating table backing `system.accounts.custom_properties`: a JSON object of each "+ "account's active custom property values, keyed by definition id."+ )+ fields: dict[str, FieldOrTable] = {+ "account_id": UUIDDatabaseField(+ name="account_id", description="Account these custom properties belong to; join to `system.accounts.id`."+ ),+ "values": StringJSONDatabaseField(+ name="values",+ description="JSON object of active custom property values keyed by definition id, coalesced to strings.",+ ),+ }++ def lazy_select(+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ return _account_custom_properties_select(table_to_add.fields_accessed)++ def to_printed_clickhouse(self, context: HogQLContext) -> str:+ return "account_custom_properties"++ def to_printed_hogql(self) -> str:+ return "account_custom_properties"++def _join_on_account_id(select: ast.SelectQuery | ast.SelectSetQuery, join_to_add: LazyJoinToAdd) -> ast.JoinExpr:return ast.JoinExpr(alias=join_to_add.to_table,@@ -173,6 +277,14 @@ def account_notebooks_join(join_to_add: LazyJoinToAdd, context: HogQLContext, noreturn _join_on_account_id(_account_notebooks_select(), join_to_add)+def account_custom_properties_join(+ join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery+) -> ast.JoinExpr:+ if not join_to_add.fields_accessed:+ raise ResolutionError("No fields requested from `accounts.custom_properties`")+ return _join_on_account_id(_account_custom_properties_select(join_to_add.fields_accessed), join_to_add)++account_tags_lazy_join: LazyJoin = LazyJoin(from_field=["id"],join_table=_AccountTagsTable(),@@ -184,3 +296,9 @@ account_notebooks_lazy_join: LazyJoin = LazyJoin(join_table=_AccountNotebooksTable(),resolver=ACCOUNT_NOTEBOOKS,)++account_custom_properties_lazy_join: LazyJoin = LazyJoin(+ from_field=["id"],+ join_table=_AccountCustomPropertiesTable(),+ resolver=ACCOUNT_CUSTOM_PROPERTIES,+)diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.pyindex 22d66cd3a931..564fd33e631e 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -18,8 +18,10 @@ from posthog.hogql.database.models import ()from posthog.hogql.database.postgres_table import PostgresTablefrom posthog.hogql.database.schema.account_aggregates import (+ _account_custom_property_values,_account_resource_notebooks,_account_tagged_items,+ account_custom_properties_lazy_join,account_notebooks_lazy_join,account_tags_lazy_join,)@@ -270,6 +272,7 @@ accounts: PostgresTable = PostgresTable(),"tags": account_tags_lazy_join,"notebooks": account_notebooks_lazy_join,+ "custom_properties": account_custom_properties_lazy_join,},)@@ -2008,6 +2011,9 @@ class SystemTables(TableNode):"_account_resource_notebooks": TableNode(name="_account_resource_notebooks", table=_account_resource_notebooks, hidden=True),+ "_account_custom_property_values": TableNode(+ name="_account_custom_property_values", table=_account_custom_property_values, hidden=True+ ),"activity_logs": TableNode(name="activity_logs", table=activity_logs),"actions": TableNode(name="actions", table=actions),"alerts": TableNode(name="alerts", table=alerts),diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 3dfa70ff7353..7f028aa10cfc 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -58,8 +58,12 @@ from products.workflows.backend.models.hog_flow.hog_flow import HogFlowif TYPE_CHECKING:from products.customer_analytics.backend.models.account import Account+ from products.customer_analytics.backend.models.custom_property_definition import CustomPropertyDefinition+ from products.customer_analytics.backend.models.custom_property_value import CustomPropertyValueelse:Account = apps.get_model("customer_analytics", "Account")+ CustomPropertyDefinition = apps.get_model("customer_analytics", "CustomPropertyDefinition")+ CustomPropertyValue = apps.get_model("customer_analytics", "CustomPropertyValue")# Only directly-queryable tables are team-scoped via a WHERE clause. Namespace nodes such as# `information_schema` carry no `table` of their own (just child catalog tables computed per-query),@@ -73,6 +77,7 @@ TEAM_ID_FILTER_PATTERNS = {# Junction tables without team_id; isolation is enforced via an account_id IN system.accounts predicate"_account_resource_notebooks": "system__accounts.team_id","_account_tagged_items": "system__accounts.team_id",+ "_account_custom_property_values": "system__accounts.team_id",}@@ -105,6 +110,7 @@ class TestSystemTablesTeamScoping(BaseTest):# isolation is covered by TestSystemAccountsLazyJoins."_account_resource_notebooks","_account_tagged_items",+ "_account_custom_property_values",# information_schema is a namespace of virtual catalog tables (tables/columns/# relationships/data_types) computed per-query from the caller's own Database object,# so it has no team_id column to isolate; behaviour is covered by TestInformationSchema.@@ -862,3 +868,57 @@ class TestSystemAccountsLazyJoins(NonAtomicBaseTest):rows_by_id = {str(row[0]): row[1] for row in response.results}assert rows_by_id[str(account.id)] == 3++ def _custom_property_value(self, account, definition, **value_kwargs):+ return CustomPropertyValue.objects.unscoped().create(+ team=self.team, account=account, definition=definition, **value_kwargs+ )++ def test_custom_properties_lazy_join_returns_value_by_definition_id(self):+ account = Account.objects.unscoped().create(team=self.team, name="A")+ definition = CustomPropertyDefinition.objects.unscoped().create(team=self.team, name="Plan")+ self._custom_property_value(account, definition, value_str="enterprise")++ response = execute_hogql_query(+ f"SELECT id, accounts.custom_properties.values.`{definition.id}` "+ "FROM system.accounts AS accounts ORDER BY name",+ team=self.team,+ user=self.user,+ )+ rows_by_id = {str(row[0]): row[1] for row in response.results}++ assert rows_by_id[str(account.id)] == "enterprise"++ def test_custom_properties_lazy_join_excludes_deleted_values(self):+ account = Account.objects.unscoped().create(team=self.team, name="A")+ definition = CustomPropertyDefinition.objects.unscoped().create(team=self.team, name="Plan")+ self._custom_property_value(account, definition, value_str="old", is_deleted=True)+ self._custom_property_value(account, definition, value_str="current")++ response = execute_hogql_query(+ f"SELECT accounts.custom_properties.values.`{definition.id}` FROM system.accounts AS accounts",+ team=self.team,+ user=self.user,+ )+ assert response.results[0][0] == "current"++ def test_custom_properties_lazy_join_isolated_per_team(self):+ # An account exists in self.team, so the query returns a row; the assertion only passes+ # if the other team's value is filtered out rather than leaking through the join.+ account = Account.objects.unscoped().create(team=self.team, name="Ours")+ other_account = Account.objects.unscoped().create(team=self.other_team, name="Theirs")+ other_definition = CustomPropertyDefinition.objects.unscoped().create(team=self.other_team, name="Plan")+ CustomPropertyValue.objects.unscoped().create(+ team=self.other_team, account=other_account, definition=other_definition, value_str="secret"+ )++ response = execute_hogql_query(+ f"SELECT id, accounts.custom_properties.values.`{other_definition.id}` FROM system.accounts AS accounts",+ team=self.team,+ user=self.user,+ )+ rows_by_id = {str(row[0]): row[1] for row in response.results}++ assert str(account.id) in rows_by_id+ assert rows_by_id[str(account.id)] != "secret"+ assert rows_by_id[str(account.id)] in (None, "")diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex c7e4507e8168..b1a4c1d5cfb6 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -2724,6 +2724,19 @@"schema_valid": true,"table": "account_notebooks","type": "lazy_table"+ },+ "custom_properties": {+ "chain": null,+ "fields": [+ "account_id",+ "values"+ ],+ "hogql_value": "custom_properties",+ "id": "custom_properties",+ "name": "custom_properties",+ "schema_valid": true,+ "table": "account_custom_properties",+ "type": "lazy_table"}},"id": "system.accounts",@@ -11141,6 +11154,19 @@"schema_valid": true,"table": "account_notebooks","type": "lazy_table"+ },+ "custom_properties": {+ "chain": null,+ "fields": [+ "account_id",+ "values"+ ],+ "hogql_value": "custom_properties",+ "id": "custom_properties",+ "name": "custom_properties",+ "schema_valid": true,+ "table": "account_custom_properties",+ "type": "lazy_table"}},"id": "system.accounts",diff --git a/posthog/hogql/database/test/test_lazy_join_resolvers.py b/posthog/hogql/database/test/test_lazy_join_resolvers.pyindex 0a8763895acc..b1809db17d6c 100644--- a/posthog/hogql/database/test/test_lazy_join_resolvers.py+++ b/posthog/hogql/database/test/test_lazy_join_resolvers.py@@ -182,6 +182,7 @@ class TestLazyJoinManifest(SimpleTestCase):"""The manifest is the closed contract a serialized Database depends on. Changing thislist changes what consumers of a serialized schema must implement — update deliberately."""assert sorted(RESOLVERS) == [+ "account_custom_properties","account_notebooks","account_tags","data_warehouse",diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.pyindex a71ca341a9e4..de354faa36fa 100644--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py@@ -16,7 +16,8 @@ from posthog.models.team import Teamfrom posthog.rbac.user_access_control import UserAccessControlErrorfrom products.customer_analytics.backend.hogql_queries.accounts_query_runner import AccountsQueryRunner-from products.customer_analytics.backend.test.factories import create_account+from products.customer_analytics.backend.models import CustomPropertyValue+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definitionfrom products.notebooks.backend.models import Notebook, ResourceNotebooktry:@@ -506,6 +507,47 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):)self.assertEqual(names, ["Match"])+ def test_custom_property_value_round_trips_through_a_selected_alias(self):+ account = create_account(team_id=self.team.id, name="A")+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")+ CustomPropertyValue.objects.unscoped().create(+ team_id=self.team.id, account=account, definition=definition, value_str="enterprise"+ )+ other = create_account(team_id=self.team.id, name="No value")++ runner = AccountsQueryRunner(+ query=AccountsQuery(select=["id", f"accounts.custom_properties.values.`{definition.id}` AS cp_x"]),+ team=self.team,+ user=self.user,+ )+ response = runner.calculate()+ id_idx, value_idx = runner.columns.index("id"), runner.columns.index("cp_x")+ values_by_id = {str(row[id_idx]): row[value_idx] for row in response.results}++ self.assertEqual(values_by_id[str(account.id)], "enterprise")+ # An account with no value for the definition aggregates to NULL/empty.+ self.assertFalse(values_by_id[str(other.id)])++ def test_numeric_custom_property_aggregates_in_metrics_mode(self):+ # Overview tiles sum/avg a numeric custom property by casting its (string) value to a float.+ definition = create_custom_property_definition(team_id=self.team.id, name="Seats", display_type="number")+ for account_name, seats in [("A", 10.0), ("B", 30.0)]:+ account = create_account(team_id=self.team.id, name=account_name)+ CustomPropertyValue.objects.unscoped().create(+ team_id=self.team.id, account=account, definition=definition, value_num=seats+ )+ create_account(team_id=self.team.id, name="No value")++ expr = f"toFloatOrNull(accounts.custom_properties.values.`{definition.id}`)"+ runner = AccountsQueryRunner(+ query=AccountsQuery(metrics=[f"sum({expr})", f"avg({expr})"], select=[]),+ team=self.team,+ user=self.user,+ )+ response = runner.calculate()+ # Sum ignores the null (no-value) account; avg averages only the two present values.+ self.assertEqual(response.metricsResults, [40.0, 20.0])+def test_validate_query_runner_access_default(self):runner = AccountsQueryRunner(query=AccountsQuery(), team=self.team)self.assertTrue(runner.validate_query_runner_access(self.user))