: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): run overview metrics in postgres (#81168)
Arthur Moreira de Deusda4281b20741
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 880061256e5d..c710da368d9f 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -281,6 +281,30 @@"required": ["kind", "accountId"],"type": "object"},+ "AccountsTableAggregateMetric": {+ "additionalProperties": false,+ "properties": {+ "aggregation": {+ "$ref": "#/definitions/AccountsTableAggregation"+ },+ "column": {+ "$ref": "#/definitions/AccountsTableCustomPropertyColumn"+ },+ "kind": {+ "const": "aggregate",+ "type": "string"+ },+ "scale": {+ "type": "number"+ }+ },+ "required": ["kind", "aggregation", "column"],+ "type": "object"+ },+ "AccountsTableAggregation": {+ "enum": ["sum", "avg", "min", "max", "median"],+ "type": "string"+ },"AccountsTableAssignedToFilter": {"additionalProperties": false,"properties": {@@ -327,6 +351,37 @@"required": ["kind"],"type": "object"},+ "AccountsTableCountMetric": {+ "additionalProperties": false,+ "properties": {+ "kind": {+ "const": "count",+ "type": "string"+ }+ },+ "required": ["kind"],+ "type": "object"+ },+ "AccountsTableCountThresholdMetric": {+ "additionalProperties": false,+ "properties": {+ "column": {+ "$ref": "#/definitions/AccountsTableCustomPropertyColumn"+ },+ "kind": {+ "const": "count_threshold",+ "type": "string"+ },+ "operator": {+ "$ref": "#/definitions/AccountsTableThresholdOperator"+ },+ "value": {+ "type": "number"+ }+ },+ "required": ["kind", "column", "operator", "value"],+ "type": "object"+ },"AccountsTableCustomPropertyColumn": {"additionalProperties": false,"properties": {@@ -451,6 +506,25 @@"required": ["kind"],"type": "object"},+ "AccountsTableMetric": {+ "description": "A typed aggregate evaluated against the filtered account set.",+ "discriminator": {+ "propertyName": "kind"+ },+ "oneOf": [+ {+ "$ref": "#/definitions/AccountsTableCountMetric"+ },+ {+ "$ref": "#/definitions/AccountsTableAggregateMetric"+ },+ {+ "$ref": "#/definitions/AccountsTableCountThresholdMetric"+ }+ ],+ "required": ["kind"],+ "type": "object"+ },"AccountsTableNoteCountColumn": {"additionalProperties": false,"properties": {@@ -486,6 +560,13 @@"limit": {"$ref": "#/definitions/positive_integer"},+ "metrics": {+ "description": "Aggregates to evaluate against the filtered account set. A metrics query skips row loading.",+ "items": {+ "$ref": "#/definitions/AccountsTableMetric"+ },+ "type": "array"+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"@@ -531,6 +612,13 @@"limit": {"$ref": "#/definitions/integer"},+ "metricsResults": {+ "description": "Aggregated values in the same order as the requested metrics.",+ "items": {+ "type": ["number", "null"]+ },+ "type": "array"+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"@@ -749,6 +837,10 @@"required": ["kind", "tagNames"],"type": "object"},+ "AccountsTableThresholdOperator": {+ "enum": ["gt", "gte", "lt", "lte", "exact", "is_not"],+ "type": "string"+ },"AccountsTableUnassignedFilter": {"additionalProperties": false,"properties": {@@ -6157,6 +6249,13 @@"limit": {"$ref": "#/definitions/integer"},+ "metricsResults": {+ "description": "Aggregated values in the same order as the requested metrics.",+ "items": {+ "type": ["number", "null"]+ },+ "type": "array"+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"@@ -18202,6 +18301,13 @@"limit": {"$ref": "#/definitions/integer"},+ "metricsResults": {+ "description": "Aggregated values in the same order as the requested metrics.",+ "items": {+ "type": ["number", "null"]+ },+ "type": "array"+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"@@ -42602,6 +42708,13 @@"limit": {"$ref": "#/definitions/integer"},+ "metricsResults": {+ "description": "Aggregated values in the same order as the requested metrics.",+ "items": {+ "type": ["number", "null"]+ },+ "type": "array"+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"@@ -44611,6 +44724,13 @@"limit": {"$ref": "#/definitions/integer"},+ "metricsResults": {+ "description": "Aggregated values in the same order as the requested metrics.",+ "items": {+ "type": ["number", "null"]+ },+ "type": "array"+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex fcae24ace7d3..18c45735fcad 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -2840,6 +2840,50 @@ export enum AccountsTableSortDirection {Descending = 'desc',}+export enum AccountsTableAggregation {+ Sum = 'sum',+ Average = 'avg',+ Minimum = 'min',+ Maximum = 'max',+ Median = 'median',+}++export enum AccountsTableThresholdOperator {+ GreaterThan = 'gt',+ GreaterThanOrEqual = 'gte',+ LessThan = 'lt',+ LessThanOrEqual = 'lte',+ Equal = 'exact',+ NotEqual = 'is_not',+}++export interface AccountsTableCountMetric {+ kind: 'count'+}++export interface AccountsTableAggregateMetric {+ kind: 'aggregate'+ aggregation: AccountsTableAggregation+ column: AccountsTableCustomPropertyColumn+ scale?: number+}++export interface AccountsTableCountThresholdMetric {+ kind: 'count_threshold'+ column: AccountsTableCustomPropertyColumn+ operator: AccountsTableThresholdOperator+ value: number+}++/**+ * A typed aggregate evaluated against the filtered account set.+ * @discriminator kind+ */+export type AccountsTableMetric =+ | AccountsTableCountMetric+ | AccountsTableAggregateMetric+ | AccountsTableCountThresholdMetric+export interface AccountsTableSort {column: AccountsTableSortableColumndirection: AccountsTableSortDirection@@ -2943,6 +2987,8 @@ export interface AccountsTableQueryResponse extends AnalyticsQueryResponseBase {hasMore: booleanlimit: integeroffset: integer+ /** Aggregated values in the same order as the requested metrics. */+ metricsResults?: (number | null)[]}export interface AccountsTableQuery extends DataNode<AccountsTableQueryResponse> {@@ -2951,6 +2997,8 @@ export interface AccountsTableQuery extends DataNode<AccountsTableQueryResponse>columns: AccountsTableColumn[]/** Filters are combined with AND. Values within tag and assignment filters use OR. */filters?: AccountsTableFilter[]+ /** Aggregates to evaluate against the filtered account set. A metrics query skips row loading. */+ metrics?: AccountsTableMetric[]sort?: AccountsTableSortlimit?: positive_integeroffset?: integerdiff --git a/posthog/schema.py b/posthog/schema.pyindex 82673e5bb98d..7c182d04c780 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -14,8 +14,10 @@ from posthog.schema_discriminators import property_filter_discriminatorfrom posthog.schema_enums import (AccessControlLevel as AccessControlLevel,AccountsTableAccountField as AccountsTableAccountField,+ AccountsTableAggregation as AccountsTableAggregation,AccountsTableCustomPropertyOperator as AccountsTableCustomPropertyOperator,AccountsTableSortDirection as AccountsTableSortDirection,+ AccountsTableThresholdOperator as AccountsTableThresholdOperator,Action as Action,AgentMode as AgentMode,AggregationAxisFormat as AggregationAxisFormat,@@ -324,6 +326,13 @@ class AccountsTableAccountIdFilter(BaseModel):kind: Literal["account_id"] = "account_id"+class AccountsTableCountMetric(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ kind: Literal["count"] = "count"++class AccountsTableCustomPropertyColumn(BaseModel):model_config = ConfigDict(extra="forbid",@@ -3054,6 +3063,16 @@ class AccountCustomPropertyFilter(BaseModel):value: list[str | float | bool] | str | float | bool | None = None+class AccountsTableAggregateMetric(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ aggregation: AccountsTableAggregation+ column: AccountsTableCustomPropertyColumn+ kind: Literal["aggregate"] = "aggregate"+ scale: float | None = None++class AccountsTableAssignedToFilter(BaseModel):model_config = ConfigDict(extra="forbid",@@ -3065,6 +3084,16 @@ class AccountsTableAssignedToFilter(BaseModel):)+class AccountsTableCountThresholdMetric(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ column: AccountsTableCustomPropertyColumn+ kind: Literal["count_threshold"] = "count_threshold"+ operator: AccountsTableThresholdOperator+ value: float++class AccountsTableCustomPropertyFilter(BaseModel):model_config = ConfigDict(extra="forbid",@@ -8650,6 +8679,10 @@ class AccountsTableQueryResponse(BaseModel):hogql: str | None = Field(default=None, description="Generated HogQL query.")kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"limit: int+ metricsResults: list[float | None] | None = Field(+ default=None,+ description="Aggregated values in the same order as the requested metrics.",+ )modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")offset: intquery_status: QueryStatus | None = Field(@@ -10413,6 +10446,10 @@ class CachedAccountsTableQueryResponse(BaseModel):kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"last_refresh: AwareDatetimelimit: int+ metricsResults: list[float | None] | None = Field(+ default=None,+ description="Aggregated values in the same order as the requested metrics.",+ )modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")next_allowed_client_refresh: AwareDatetimeoffset: int@@ -15808,6 +15845,10 @@ class Response23(BaseModel):hogql: str | None = Field(default=None, description="Generated HogQL query.")kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"limit: int+ metricsResults: list[float | None] | None = Field(+ default=None,+ description="Aggregated values in the same order as the requested metrics.",+ )modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")offset: intquery_status: QueryStatus | None = Field(@@ -21161,6 +21202,10 @@ class QueryResponseAlternative58(BaseModel):hogql: str | None = Field(default=None, description="Generated HogQL query.")kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"limit: int+ metricsResults: list[float | None] | None = Field(+ default=None,+ description="Aggregated values in the same order as the requested metrics.",+ )modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")offset: intquery_status: QueryStatus | None = Field(@@ -22354,6 +22399,10 @@ class QueryResponseAlternative88(BaseModel):hogql: str | None = Field(default=None, description="Generated HogQL query.")kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"limit: int+ metricsResults: list[float | None] | None = Field(+ default=None,+ description="Aggregated values in the same order as the requested metrics.",+ )modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")offset: intquery_status: QueryStatus | None = Field(@@ -24328,6 +24377,12 @@ class AccountsTableQuery(BaseModel):)kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"limit: conint(ge=1) | None = None+ metrics: (+ list[AccountsTableCountMetric | AccountsTableAggregateMetric | AccountsTableCountThresholdMetric] | None+ ) = Field(+ default=None,+ description=("Aggregates to evaluate against the filtered account set. A metrics query skips row loading."),+ )modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")offset: int | None = Noneresponse: AccountsTableQueryResponse | None = Nonediff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 533de3164c87..ce17c9449d3c 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -42,6 +42,14 @@ class AccountsTableAccountField(StrEnum):ZENDESK_ID = "zendesk_id"+class AccountsTableAggregation(StrEnum):+ SUM = "sum"+ AVG = "avg"+ MIN = "min"+ MAX = "max"+ MEDIAN = "median"++class WindowDays(float, Enum):NUMBER_7 = 7NUMBER_14 = 14@@ -72,6 +80,15 @@ class AccountsTableSortDirection(StrEnum):DESC = "desc"+class AccountsTableThresholdOperator(StrEnum):+ GT = "gt"+ GTE = "gte"+ LT = "lt"+ LTE = "lte"+ EXACT = "exact"+ IS_NOT = "is_not"++class MathGroupTypeIndex(float, Enum):NUMBER_0 = 0NUMBER_1 = 1diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex f926e473d565..96f942a5a528 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -30,6 +30,8 @@ from django.core.cache import cachefrom django.core.exceptions import ValidationErrorfrom django.db import IntegrityError, transactionfrom django.db.models import (+ Aggregate,+ Avg,BooleanField,CharField,Count,@@ -39,11 +41,14 @@ from django.db.models import (Field,FloatField,IntegerField,+ Max,+ Min,OuterRef,Prefetch,Q,QuerySet,Subquery,+ Sum,TextField,Value,)@@ -2479,6 +2484,90 @@ def _apply_account_table_sort(return queryset.order_by(primary_order, "id")+class _PercentileCont(Aggregate):+ function = "PERCENTILE_CONT"+ template = "%(function)s(0.5) WITHIN GROUP (ORDER BY %(expressions)s)"+ output_field = FloatField()+++def query_accounts_metrics(+ *,+ team_id: int,+ user_access_control: "UserAccessControl",+ filters: tuple[contracts.AccountTableFilter, ...],+ metrics: tuple[contracts.AccountTableMetric, ...],+) -> list[float | int | None]:+ definition_ids = frozenset(+ metric.definition_id+ for metric in metrics+ if isinstance(metric, contracts.AccountTableAggregateMetric | contracts.AccountTableCountThresholdMetric)+ )+ custom_property_display_types = _validate_account_table_definitions(+ team_id=team_id,+ selection=contracts.AccountTableColumnSelection(custom_property_definition_ids=definition_ids),+ filters=filters,+ sort=None,+ )+ for definition_id in definition_ids:+ if DATA_TYPE_BY_DISPLAY_TYPE[custom_property_display_types[definition_id]] != DataType.NUMERIC:+ raise InvalidAccountTableColumn("Account table metrics require numeric custom properties.")++ accounts = _apply_account_table_filters(+ _accounts_queryset(team_id, user_access_control),+ team_id=team_id,+ filters=filters,+ custom_property_display_types=custom_property_display_types,+ )+ results: list[float | int | None] = [None] * len(metrics)+ for index, metric in enumerate(metrics):+ if isinstance(metric, contracts.AccountTableCountMetric):+ results[index] = accounts.count()++ aggregate_expressions: dict[str, Aggregate] = {}+ for index, metric in enumerate(metrics):+ alias = f"metric_{index}"+ if isinstance(metric, contracts.AccountTableAggregateMetric):+ aggregate_type = {+ contracts.AccountTableAggregation.SUM: Sum,+ contracts.AccountTableAggregation.AVERAGE: Avg,+ contracts.AccountTableAggregation.MINIMUM: Min,+ contracts.AccountTableAggregation.MAXIMUM: Max,+ contracts.AccountTableAggregation.MEDIAN: _PercentileCont,+ }[metric.aggregation]+ aggregate_expressions[alias] = aggregate_type(+ "value_num",+ filter=Q(definition_id=metric.definition_id),+ )+ elif isinstance(metric, contracts.AccountTableCountThresholdMetric):+ comparison = {+ contracts.AccountTableThresholdOperator.GREATER_THAN: Q(value_num__gt=metric.value),+ contracts.AccountTableThresholdOperator.GREATER_THAN_OR_EQUAL: Q(value_num__gte=metric.value),+ contracts.AccountTableThresholdOperator.LESS_THAN: Q(value_num__lt=metric.value),+ contracts.AccountTableThresholdOperator.LESS_THAN_OR_EQUAL: Q(value_num__lte=metric.value),+ contracts.AccountTableThresholdOperator.EQUAL: Q(value_num=metric.value),+ contracts.AccountTableThresholdOperator.NOT_EQUAL: ~Q(value_num=metric.value),+ }[metric.operator]+ aggregate_expressions[alias] = Count(+ "account_id",+ filter=Q(definition_id=metric.definition_id) & comparison,+ )++ if aggregate_expressions:+ values = CustomPropertyValue.objects.for_team(team_id).filter(+ account_id__in=accounts.order_by().values("id"),+ is_deleted=False,+ value_num__isnull=False,+ )+ aggregated = values.aggregate(**aggregate_expressions)+ for index, metric in enumerate(metrics):+ value = aggregated.get(f"metric_{index}")+ if isinstance(metric, contracts.AccountTableAggregateMetric) and value is not None:+ results[index] = float(value) * (metric.scale if metric.scale is not None else 1)+ elif isinstance(metric, contracts.AccountTableCountThresholdMetric):+ results[index] = int(value or 0)+ return results++def query_accounts_table(*,team_id: int,diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 8beccde4139d..07fbccd05d5d 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -282,6 +282,45 @@ class AccountTableSort:definition_id: UUID | None = None+class AccountTableAggregation(str, Enum):+ SUM = "sum"+ AVERAGE = "avg"+ MINIMUM = "min"+ MAXIMUM = "max"+ MEDIAN = "median"+++class AccountTableThresholdOperator(str, Enum):+ GREATER_THAN = "gt"+ GREATER_THAN_OR_EQUAL = "gte"+ LESS_THAN = "lt"+ LESS_THAN_OR_EQUAL = "lte"+ EQUAL = "exact"+ NOT_EQUAL = "is_not"+++@dataclass(frozen=True, kw_only=True)+class AccountTableCountMetric:+ pass+++@dataclass(frozen=True, kw_only=True)+class AccountTableAggregateMetric:+ aggregation: AccountTableAggregation+ definition_id: UUID+ scale: float | None = None+++@dataclass(frozen=True, kw_only=True)+class AccountTableCountThresholdMetric:+ definition_id: UUID+ operator: AccountTableThresholdOperator+ value: float+++AccountTableMetric = AccountTableCountMetric | AccountTableAggregateMetric | AccountTableCountThresholdMetric++@dataclass(frozen=True, kw_only=True)class AccountTableCustomPropertyHistoryPoint:timestamp: datetimediff --git a/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.pyindex db0217412c63..dcf874a806a6 100644--- a/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py+++ b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py@@ -6,7 +6,10 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.schema import (AccountsTableAccountFieldColumn,AccountsTableAccountIdFilter,+ AccountsTableAggregateMetric,AccountsTableAssignedToFilter,+ AccountsTableCountMetric,+ AccountsTableCountThresholdMetric,AccountsTableCustomPropertyColumn,AccountsTableCustomPropertyFilter,AccountsTableCustomPropertyHistoryColumn,@@ -34,6 +37,7 @@ from products.customer_analytics.backend.facade import api, contractsACCOUNTS_TABLE_MAX_COLUMNS = 100ACCOUNTS_TABLE_MAX_FILTERS = 50ACCOUNTS_TABLE_MAX_FILTER_VALUES = 100+ACCOUNTS_TABLE_MAX_METRICS = 5ACCOUNTS_TABLE_MAX_PAGE_SIZE = 500ACCOUNTS_TABLE_MAX_STRING_LENGTH = 1_000@@ -178,6 +182,36 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])except ValueError as error:raise ValidationError("Account table sort definition IDs must be valid UUIDs.") from error+ def _metrics(self) -> tuple[contracts.AccountTableMetric, ...]:+ query_metrics = self.query.metrics or []+ if len(query_metrics) > ACCOUNTS_TABLE_MAX_METRICS:+ raise ValidationError(f"Account table queries support up to {ACCOUNTS_TABLE_MAX_METRICS} metrics.")++ metrics: list[contracts.AccountTableMetric] = []+ try:+ for metric in query_metrics:+ if isinstance(metric, AccountsTableCountMetric):+ metrics.append(contracts.AccountTableCountMetric())+ elif isinstance(metric, AccountsTableAggregateMetric):+ metrics.append(+ contracts.AccountTableAggregateMetric(+ aggregation=contracts.AccountTableAggregation(metric.aggregation.value),+ definition_id=UUID(metric.column.definitionId),+ scale=metric.scale,+ )+ )+ elif isinstance(metric, AccountsTableCountThresholdMetric):+ metrics.append(+ contracts.AccountTableCountThresholdMetric(+ definition_id=UUID(metric.column.definitionId),+ operator=contracts.AccountTableThresholdOperator(metric.operator.value),+ value=metric.value,+ )+ )+ except ValueError as error:+ raise ValidationError("Account table metric definition IDs must be valid UUIDs.") from error+ return tuple(metrics)+def _calculate(self) -> AccountsTableQueryResponse:user_access_control = self.user_access_controlif user_access_control is None:@@ -189,13 +223,28 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])ACCOUNTS_TABLE_MAX_PAGE_SIZE,)offset = max(self.query.offset or 0, 0)+ filters = self._filters()try:+ if self.query.metrics is not None:+ metrics_results = api.query_accounts_metrics(+ team_id=self.team.id,+ user_access_control=user_access_control,+ filters=filters,+ metrics=self._metrics(),+ )+ return AccountsTableQueryResponse(+ results=[],+ hasMore=False,+ limit=limit,+ offset=offset,+ metricsResults=metrics_results,+ )page = api.query_accounts_table(team_id=self.team.id,user_access_control=user_access_control,selection=self._column_selection(),- filters=self._filters(),+ filters=filters,sort=self._sort(),offset=offset,limit=limit,diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.pyindex 64ef289c41d1..0094fdd1b057 100644--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py@@ -15,7 +15,11 @@ from posthog.schema import (AccountsTableAccountField,AccountsTableAccountFieldColumn,AccountsTableAccountIdFilter,+ AccountsTableAggregateMetric,+ AccountsTableAggregation,AccountsTableAssignedToFilter,+ AccountsTableCountMetric,+ AccountsTableCountThresholdMetric,AccountsTableCustomPropertyColumn,AccountsTableCustomPropertyFilter,AccountsTableCustomPropertyHistoryColumn,@@ -29,6 +33,7 @@ from posthog.schema import (AccountsTableSortDirection,AccountsTableTagsColumn,AccountsTableTagsFilter,+ AccountsTableThresholdOperator,AccountsTableUnassignedFilter,)@@ -43,6 +48,7 @@ from products.customer_analytics.backend.hogql_queries.accounts_table_query_runnACCOUNTS_TABLE_MAX_COLUMNS,ACCOUNTS_TABLE_MAX_FILTER_VALUES,ACCOUNTS_TABLE_MAX_FILTERS,+ ACCOUNTS_TABLE_MAX_METRICS,ACCOUNTS_TABLE_MAX_PAGE_SIZE,ACCOUNTS_TABLE_MAX_STRING_LENGTH,AccountsTableQueryRunner,@@ -162,6 +168,78 @@ class TestAccountsTableQueryRunner(BaseTest):}assert empty_row.customPropertyHistory == {str(numeric_definition.id): []}+ def test_calculates_typed_metrics_against_the_filtered_account_set(self) -> None:+ definition = create_custom_property_definition(+ team_id=self.team.id,+ name="MRR",+ display_type=DisplayType.CURRENCY,+ )+ high = create_account(team_id=self.team.id, name="High")+ low = create_account(team_id=self.team.id, name="Low")+ create_account(team_id=self.team.id, name="Unset")+ CustomPropertyValue.objects.unscoped().create(+ team=self.team,+ account=high,+ definition=definition,+ value_num=20,+ )+ CustomPropertyValue.objects.unscoped().create(+ team=self.team,+ account=low,+ definition=definition,+ value_num=5,+ )+ column = AccountsTableCustomPropertyColumn(definitionId=str(definition.id))++ response = self._run(+ AccountsTableQuery(+ columns=[],+ filters=[],+ metrics=[+ AccountsTableCountMetric(),+ AccountsTableAggregateMetric(+ aggregation=AccountsTableAggregation.SUM,+ column=column,+ scale=12,+ ),+ AccountsTableAggregateMetric(+ aggregation=AccountsTableAggregation.AVG,+ column=column,+ ),+ AccountsTableAggregateMetric(+ aggregation=AccountsTableAggregation.MIN,+ column=column,+ ),+ AccountsTableAggregateMetric(+ aggregation=AccountsTableAggregation.MAX,+ column=column,+ ),+ ],+ )+ )+ remaining_response = self._run(+ AccountsTableQuery(+ columns=[],+ filters=[],+ metrics=[+ AccountsTableAggregateMetric(+ aggregation=AccountsTableAggregation.MEDIAN,+ column=column,+ ),+ AccountsTableCountThresholdMetric(+ column=column,+ operator=AccountsTableThresholdOperator.GT,+ value=10,+ ),+ ],+ )+ )++ assert response.results == []+ assert response.metricsResults == [3, 300.0, 12.5, 5.0, 20.0]+ assert remaining_response.results == []+ assert remaining_response.metricsResults == [12.5, 1]+def test_hydrates_custom_properties_with_bounded_queries(self) -> None:definition = create_custom_property_definition(team_id=self.team.id,@@ -192,10 +270,18 @@ class TestAccountsTableQueryRunner(BaseTest):assert {row.custom_properties[definition.id] for row in page.rows} == {0.0, 1.0, 2.0}- def test_caps_selected_columns_and_page_size(self) -> None:+ def test_caps_selected_columns_metrics_and_page_size(self) -> None:with self.assertRaises(ValidationError):self._run(AccountsTableQuery(columns=[AccountsTableTagsColumn()] * (ACCOUNTS_TABLE_MAX_COLUMNS + 1)))+ with self.assertRaises(ValidationError):+ self._run(+ AccountsTableQuery(+ columns=[],+ metrics=[AccountsTableCountMetric()] * (ACCOUNTS_TABLE_MAX_METRICS + 1),+ )+ )+response = self._run(AccountsTableQuery(columns=[], limit=ACCOUNTS_TABLE_MAX_PAGE_SIZE + 1))assert response.limit == ACCOUNTS_TABLE_MAX_PAGE_SIZEdiff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex c2b196796954..1ebde5df8ad7 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -14,7 +14,7 @@ An **Account** is a customer organization. The list is a HogQL-backed table over## Architecture-The scene renders `AccountsTabContent`, which binds **two** `dataNodeLogic` instances (keys from `../../constants`): `ACCOUNTS_HOGQL_DATA_NODE_KEY` for the list rows (`accountsLogic.accountsQuerySource`, held at null until the relationship definitions settle) and `ACCOUNTS_METRICS_DATA_NODE_KEY` for the overview-tile aggregations (`accountsLogic.metricsQuery`). The list source is the existing `AccountsQuery` by default. `CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES` switches supported state to `AccountsTableQuery`; unsupported columns and tile filters fall back to HogQL. Metrics remain on the HogQL runner. The requests stay split so slower aggregations never block list rows. The table reads the list node; `accountsOverviewTilesLogic` reads the metrics node.+The scene renders `AccountsTabContent`, which binds **two** `dataNodeLogic` instances (keys from `../../constants`): `ACCOUNTS_HOGQL_DATA_NODE_KEY` for list rows and `ACCOUNTS_METRICS_DATA_NODE_KEY` for overview-tile aggregations. The overview uses a metrics-only `AccountsTableQuery` against Postgres whenever its filters translate to typed filters, with the existing `AccountsQuery` retained as a compatibility fallback. Each request carries its own loading state, and the metrics provider only wraps `AccountsOverviewTiles`, so slower aggregations never block list rows.```textAccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, accountsLogic.accountsQuerySource) [list rows]@@ -46,7 +46,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. || `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API), and the custom-property definitions: it loads them, seeds `propertyDefinitionsModel` (so the filter UI resolves per-type operator sets), and exposes `customPropertyTaxonomicOptions` / `customPropertyDefinitionsById`. When `CUSTOMER_ANALYTICS_ACCOUNTS_HOGQL_CLEANUP` is enabled, the picker only offers Postgres-backed account fields, tags, notes, relationships, and custom properties. || `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |-| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); its `metrics` feed `accountsLogic.metricsQuery`, the separate metrics-only data node (key `ACCOUNTS_METRICS_DATA_NODE_KEY`) it reads `response`/`responseLoading` back from — independent of the list rows. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |+| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`). It exposes the existing metric expressions plus typed Postgres metrics and reads results from the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. || `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). || `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated client-side. A missing view (local dev) degrades to the normal empty state. || `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |@@ -61,7 +61,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc`accountsLogic.hogqlQuery` builds a `DataTableNode` wrapping the existing `AccountsQuery`. `accountsTableQueryPlan` translates the same selected columns, filters, custom-property display windows, and server-side sort into a typed `AccountsTableQuery`. When the Postgres flag is enabled and translation is complete, `accountsQuerySource` runs that query instead. The translator reads the live reducers after saved-view or URL restoration, so storage stays backward compatible. A tile filter or unsupported legacy expression returns no plan and keeps the list on HogQL. `tableRowsTransformer` converts keyed `AccountsTableRow`s into arrays aligned to `visibleColumnNames`, preserving the current table and cell components during rollout.-The overview-tile `metrics` remain a separate metrics-only `AccountsQuery` (`metrics` set, no `select`; `null` when there are no tiles or while definitions are still loading). The "My accounts" checkbox remains a client-side shortcut that resolves to the current user's explicit ID before either list query is built, so shared URLs remain viewer-independent. Two cell shapes matter:+Overview metrics run separately through `accountsLogic.metricsQuery`. Supported filters translate into a metrics-only `AccountsTableQuery` (`metrics` set and `columns: []`) that calculates count, sum, average, minimum, maximum, median, scaling, and threshold counts in Postgres. Filters that still require the compatibility path retain the metrics-only `AccountsQuery` until the final migration removes those states. The "My accounts" checkbox remains a client-side shortcut that resolves to the current user's explicit ID before either list query is built, so shared URLs remain viewer-independent. Two cell shapes matter:- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — emitted as `tuple(name, external_id, id)`, read as `{ name, external_id, id }`. This is the row's identity: `id` (the account PK) drives expansion/scroll/role updates; `external_id` is the copy-able group key. `getNameCell()` in `AccountsHogQLTable.tsx` is the canonical accessor; never assume a column index. In `NameCell` the name renders as the prominent (`font-semibold`) primary label: a plain click opens the account details inline (toggles the row's expansion via `accountsExpansionLogic`, firing `AccountOpened` on open), while the `<Link>` href points at `urls.customerAnalyticsAccount(id)` so cmd/ctrl-click opens the account's deep-link page in a new tab. The `external_id` sits beneath it as de-emphasized (`text-xs text-muted`) copy-to-clipboard text.- **relationship columns** — backed by the ``accounts.relationships.values.`<definition_id>` `` lazy join, emitted as the **array of active assignee user ids** (`[]` when unassigned). The legacy names `csm`/`account_executive`/`account_owner` remain the STORED column names (in defaults, saved views, and URL state) and are translated into the lazy-join expression at query-build time by `translateSelectColumns` in `accountsColumnConfigLogic`, matched by seeded definition name (`LEGACY_ROLE_COLUMNS`); a legacy column with no matching definition is dropped from the query. Other definitions are pickable from the "Relationships" column group with opaque `rel_<id>` aliases, resolved back via `aliasToRelationshipDefinition`. Cells render `RelationshipCell`: single-holder definitions get an editable `MemberSelect` (writes via the relationships assign/end endpoints — assign auto-ends the previous holder server-side); multi-holder definitions render read-only. User ids resolve to members via `membersLogic` (loaded up front in `accountsLogic.afterMount`). Sorting uses the alias directly (arrays of ids — deterministic but not email order).diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex 0b7829b7943a..693a92c2e49d 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -177,11 +177,24 @@ const EXPANDED_ROW_TEST_OPTIONS = {function mockAccountsQuery(rows: AccountRow[]): (info: MockResolverInfo) => Promise<[number, unknown] | undefined> {return async ({ request }) => {- const body = (await request.json()) as { query?: { kind?: string } }- const kind = body?.query?.kind- if (kind === 'AccountsQuery') {+ const body = (await request.json()) as { query?: { kind?: string; metrics?: unknown[] } }+ const query = body?.query+ if (query?.kind === 'AccountsQuery') {return [200, buildAccountsQueryResponse(rows)]}+ if (query?.kind === 'AccountsTableQuery' && query.metrics) {+ return [+ 200,+ {+ kind: 'AccountsTableQuery',+ results: [],+ hasMore: false,+ limit: 100,+ offset: 0,+ metricsResults: [rows.length],+ },+ ]+ }return undefined}}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.tsindex 2236ca20f7fa..5597a21e6dfd 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts@@ -9,7 +9,11 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'-import type { AccountsQuery, AccountsTableQuery } from '~/queries/schema/schema-general'+import {+ AccountsTableCustomPropertyOperator,+ type AccountsQuery,+ type AccountsTableQuery,+} from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import type { UserBasicType, UserType } from '~/types'@@ -72,6 +76,16 @@ const mockPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof acconst CSM_DEFINITION_ID = '11111111-2222-3333-4444-555555555555'const AE_DEFINITION_ID = '66666666-7777-8888-9999-aaaaaaaaaaaa'const OWNER_DEFINITION_ID = 'bbbbbbbb-cccc-dddd-eeee-ffffffffffff'+const TILE_FILTER = {+ tileId: 'tile-1',+ expression: 'count() > 5',+ filter: {+ kind: 'custom_property' as const,+ definitionId: CSM_DEFINITION_ID,+ operator: AccountsTableCustomPropertyOperator.GreaterThan,+ values: [5],+ },+}const DEFINITIONS: AccountRelationshipDefinitionApi[] = [{ id: CSM_DEFINITION_ID, name: 'CSM', description: null, is_single_holder: true },@@ -163,7 +177,7 @@ describe('accountsLogic', () => {{ kind: 'relationship', definitionId: AE_DEFINITION_ID },{ kind: 'relationship', definitionId: OWNER_DEFINITION_ID },])- expect(logic.values.metricsQuery?.kind).toBe('AccountsQuery')+ expect(logic.values.metricsQuery?.kind).toBe('AccountsTableQuery')})it('keeps the DataTable data node on the active Postgres source for refreshes', () => {@@ -206,7 +220,7 @@ describe('accountsLogic', () => {},] as DataTableRow[]- logic.actions.setTileFilter({ tileId: 'tile', expression: 'count() > 1' })+ logic.actions.setTileFilter({ ...TILE_FILTER, tileId: 'tile', expression: 'count() > 1' })expect(logic.values.accountsQuerySource?.kind).toBe('AccountsQuery')expect(logic.values.tableRowsTransformer?.(keyedRows)[0].result).toEqual([@@ -248,7 +262,7 @@ describe('accountsLogic', () => {featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES], {[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES]: true,})- logic.actions.setTileFilter({ tileId: 'tile', expression: 'count() > 1' })+ logic.actions.setTileFilter({ ...TILE_FILTER, tileId: 'tile', expression: 'count() > 1' })expect(logic.values.accountsQuerySource?.kind).toBe('AccountsQuery')})@@ -292,10 +306,10 @@ describe('accountsLogic', () => {expect(source.metrics).toBeUndefined()})- it('exposes the overview tile metrics on a separate metrics-only query (no select)', () => {- const metricsQuery = logic.values.metricsQuery as AccountsQuery- expect(metricsQuery.metrics).toEqual(['count()'])- expect(metricsQuery.select).toBeUndefined()+ it('exposes the overview tile metrics on a separate Postgres metrics query', () => {+ const metricsQuery = logic.values.metricsQuery as AccountsTableQuery+ expect(metricsQuery.metrics).toEqual([{ kind: 'count' }])+ expect(metricsQuery.columns).toEqual([])})it('setAllRolesUnassigned toggles the flag', () => {@@ -659,7 +673,7 @@ describe('accountsLogic', () => {logic.actions.setTagsFilter(['enterprise'])logic.actions.setAssignedToFilter([7])logic.actions.setSortOrder({ column: 'name', direction: 'desc' })- logic.actions.setTileFilter({ tileId: 'tile-1', expression: 'count() > 5' })+ logic.actions.setTileFilter(TILE_FILTER)}).toFinishAllListeners()expect(router.values.hashParams.view).toEqual({@@ -667,7 +681,7 @@ describe('accountsLogic', () => {tags: ['enterprise'],assignedTo: [7],sort: { column: 'name', direction: 'desc' },- tileFilter: { tileId: 'tile-1', expression: 'count() > 5' },+ tileFilter: TILE_FILTER,})})@@ -681,7 +695,7 @@ describe('accountsLogic', () => {})it('restores filters, sort, and tile filter from the view hash param', async () => {- const tileFilter = { tileId: 'tile-1', expression: 'count() > 5' }+ const tileFilter = TILE_FILTERrouter.actions.push(urls.customerAnalyticsAccounts(),{},diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex 2cf338927582..fb06115009cf 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -18,6 +18,7 @@ import { type DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNodeimport type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'import {AccountsQuery,+ AccountsTableMetric,AccountsTableQuery,DataNode,DataTableNode,@@ -212,6 +213,7 @@ export interface accountsLogicValues {selectColumns: string[] // accountsColumnConfigLogicvisibleColumnNames: string[] // accountsColumnConfigLogicoverviewMetrics: string[] // accountsOverviewTilesLogic+ overviewPostgresMetrics: AccountsTableMetric[] // accountsOverviewTilesLogictileFilter: TileFilter | null // accountsOverviewTilesLogicmineOnly: boolean // customerAnalyticsSceneLogiclistHasMoreData: boolean // dataNodeLogic@@ -235,7 +237,7 @@ export interface accountsLogicValues {isRoleSaving: (accountId: string, column: string) => booleanisTagsSaving: (accountId: string) => booleanlistPaginated: boolean- metricsQuery: AccountsQuery | null+ metricsQuery: AccountsQuery | AccountsTableQuery | nullpostgresAccountsEnabled: booleanrelationshipOverrides: Record<string, number[]>savingRoles: Record<string, true>@@ -511,6 +513,8 @@ export interface accountsLogicMeta {) => ((rows: DataTableRow[]) => DataTableRow[]) | undefinedmetricsQuery: (overviewMetrics: string[],+ overviewPostgresMetrics: AccountsTableMetric[],+ accountsTableQueryPlanInput: BuildAccountsTableQueryPlanInput,searchQuery: string,tagsFilter: string[],allRolesUnassigned: boolean,@@ -520,7 +524,7 @@ export interface accountsLogicMeta {customPropertyFilters: AccountCustomPropertyFilter[],customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,relationshipDefinitionsLoaded: boolean- ) => AccountsQuery | null+ ) => AccountsQuery | AccountsTableQuery | null}}@@ -554,7 +558,7 @@ export const accountsLogic = kea<accountsLogicType>(['columnDisplay',],accountsOverviewTilesLogic,- ['metrics as overviewMetrics', 'tileFilter'],+ ['metrics as overviewMetrics', 'postgresMetrics as overviewPostgresMetrics', 'tileFilter'],customerAnalyticsSceneLogic,['mineOnly'],dataNodeLogic({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY } as DataNodeLogicProps),@@ -1042,6 +1046,8 @@ export const accountsLogic = kea<accountsLogicType>([metricsQuery: [(s) => [s.overviewMetrics,+ s.overviewPostgresMetrics,+ s.accountsTableQueryPlanInput,s.searchQuery,s.tagsFilter,s.allRolesUnassigned,@@ -1054,6 +1060,8 @@ export const accountsLogic = kea<accountsLogicType>([],(overviewMetrics: string[],+ overviewPostgresMetrics: AccountsTableMetric[],+ accountsTableQueryPlanInput: BuildAccountsTableQueryPlanInput,searchQuery: string,tagsFilter: string[],allRolesUnassigned: boolean,@@ -1063,10 +1071,29 @@ export const accountsLogic = kea<accountsLogicType>([customPropertyFilters: AccountCustomPropertyFilter[],customPropertyDefinitionsById: Record<string, CustomPropertyDefinitionApi>,relationshipDefinitionsLoaded: boolean- ): AccountsQuery | null => {+ ): AccountsQuery | AccountsTableQuery | null => {if (overviewMetrics.length === 0 || !relationshipDefinitionsLoaded) {return null}+ const postgresPlan = buildAccountsTableQueryPlan({+ ...accountsTableQueryPlanInput,+ querySelectColumns: [],+ visibleColumnNames: [],+ sortOrder: null,+ canSortClientSide: true,+ })+ if (postgresPlan && overviewPostgresMetrics.length === overviewMetrics.length) {+ return {+ ...postgresPlan.query,+ columns: [],+ metrics: overviewPostgresMetrics,+ sort: undefined,+ tags: {+ ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,+ name: 'customer_analytics_accounts_overview',+ },+ }+ }const source: AccountsQuery = {kind: NodeKind.AccountsQuery,metrics: overviewMetrics,diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.tsindex d2deaabf0173..37c35c9eab13 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.test.ts@@ -11,10 +11,10 @@ import {isTileClickable,numericColumnOptions,parseTileValues,- stripHogqlAlias,+ stripColumnAlias,tileCaption,tileFilterFor,- tileMetricExpression,+ tileQueryMetric,tileToRowFilter,} from './accountsOverviewTilesLogic'import {@@ -24,17 +24,17 @@ import {MAX_ACCOUNTS_OVERVIEW_TILES,} from './constants'-describe('stripHogqlAlias', () => {+describe('stripColumnAlias', () => {it('strips a trailing AS alias', () => {- expect(stripHogqlAlias('accounts.health.score AS score')).toBe('accounts.health.score')+ expect(stripColumnAlias('accounts.health.score AS score')).toBe('accounts.health.score')})it('leaves a plain expression untouched', () => {- expect(stripHogqlAlias('health_score')).toBe('health_score')+ expect(stripColumnAlias('health_score')).toBe('health_score')})it('does not strip AS in the middle', () => {- expect(stripHogqlAlias("toString(JSONExtract(properties, 'score', 'Nullable(Int64)'))")).toBe(+ expect(stripColumnAlias("toString(JSONExtract(properties, 'score', 'Nullable(Int64)'))")).toBe("toString(JSONExtract(properties, 'score', 'Nullable(Int64)'))")})@@ -78,7 +78,6 @@ describe('numericColumnOptions', () => {label: 'health',options: [{ name: 'score', expression: 'accounts.health.score AS score', type: 'float' }],},- { key: 'sql_expression', label: 'SQL expression', options: [], isFreeform: true },])expect(options).toEqual([{ name: 'health_score', expression: 'health_score', type: 'integer' },@@ -107,50 +106,47 @@ describe('numericColumnOptions', () => {})})-describe('tileMetricExpression', () => {- // Each column-aggregation metric type must emit its own HogQL aggregate function- // (the type name is the function name); a regression collapsing them to one fn- // would silently query the wrong statistic.+describe('tileQueryMetric', () => {+ const columnExpression = 'toFloatOrNull(accounts.custom_properties.values.`11111111-2222-3333-4444-555555555555`)'+it.each([- [{ type: 'count' as const }, 'count()'],- [{ type: 'sum' as const, columnExpression: 'health_score', columnLabel: 'Health score' }, 'sum(health_score)'],- [{ type: 'avg' as const, columnExpression: 'health_score', columnLabel: 'Health score' }, 'avg(health_score)'],- [{ type: 'min' as const, columnExpression: 'health_score', columnLabel: 'Health score' }, 'min(health_score)'],- [{ type: 'max' as const, columnExpression: 'health_score', columnLabel: 'Health score' }, 'max(health_score)'],+ [{ type: 'count' as const }, { kind: 'count' }],[- { type: 'median' as const, columnExpression: 'health_score', columnLabel: 'Health score' },- 'median(health_score)',+ { type: 'sum' as const, columnExpression, columnLabel: 'Health score', scale: 12 },+ {+ kind: 'aggregate',+ aggregation: 'sum',+ column: { kind: 'custom_property', definitionId: '11111111-2222-3333-4444-555555555555' },+ scale: 12,+ },],[{type: 'count_threshold' as const,- columnExpression: 'health_score',+ columnExpression,columnLabel: 'Health score',operator: '<' as const,value: 6,},- 'countIf(health_score < 6)',+ {+ kind: 'count_threshold',+ column: { kind: 'custom_property', definitionId: '11111111-2222-3333-4444-555555555555' },+ operator: 'lt',+ value: 6,+ },],- ])('produces the right HogQL fragment for %o', (metric, expected) => {- expect(tileMetricExpression({ id: 'x', label: 'l', metric })).toBe(expected)+ ])('produces the typed metric for %o', (metric, expected) => {+ expect(tileQueryMetric({ id: 'x', label: 'l', metric })).toEqual(expected)})- // The optional scale multiplier wraps the aggregation; no-op values (1, missing,- // non-finite) must not append a stray `* n` that would change or break the query.- it.each([- [12, 'sum(mrr) * 12'],- [0.5, 'sum(mrr) * 0.5'],- [1, 'sum(mrr)'],- [undefined, 'sum(mrr)'],- [NaN, 'sum(mrr)'],- ])('applies scale %p to a column aggregation', (scale, expected) => {+ it('rejects columns outside the typed Postgres query', () => {expect(- tileMetricExpression({+ tileQueryMetric({id: 'x',label: 'l',- metric: { type: 'sum', columnExpression: 'mrr', columnLabel: 'MRR', scale },+ metric: { type: 'sum', columnExpression: 'warehouse.mrr', columnLabel: 'MRR' },})- ).toBe(expected)+ ).toBeNull()})})@@ -184,7 +180,8 @@ describe('tileCaption', () => {label: 'At risk',metric: {type: 'count_threshold',- columnExpression: 'health_score',+ columnExpression:+ 'toFloatOrNull(accounts.custom_properties.values.`11111111-2222-3333-4444-555555555555`)',columnLabel: 'Health score',operator: '<',value: 6,@@ -203,7 +200,7 @@ describe('tileToRowFilter / isTileClickable', () => {label: 'At risk',metric: {type: 'count_threshold',- columnExpression: 'health_score',+ columnExpression: 'toFloatOrNull(accounts.custom_properties.values.`11111111-2222-3333-4444-555555555555`)',columnLabel: 'Health score',operator: '<',value: 6,@@ -211,7 +208,12 @@ describe('tileToRowFilter / isTileClickable', () => {}it('maps a threshold tile to its row predicate', () => {- expect(tileToRowFilter(thresholdTile)).toBe('health_score < 6')+ expect(tileToRowFilter(thresholdTile)).toEqual({+ kind: 'custom_property',+ definitionId: '11111111-2222-3333-4444-555555555555',+ operator: 'lt',+ values: [6],+ })expect(isTileClickable(thresholdTile)).toBe(true)})@@ -230,13 +232,23 @@ describe('tileFilterFor', () => {label: 'At risk',metric: {type: 'count_threshold',- columnExpression: 'health_score',+ columnExpression:+ 'toFloatOrNull(accounts.custom_properties.values.`11111111-2222-3333-4444-555555555555`)',columnLabel: 'Health score',operator: '<',value: 6,},})- ).toEqual({ tileId: 'b', expression: 'health_score < 6' })+ ).toEqual({+ tileId: 'b',+ expression: 'toFloatOrNull(accounts.custom_properties.values.`11111111-2222-3333-4444-555555555555`) < 6',+ filter: {+ kind: 'custom_property',+ definitionId: '11111111-2222-3333-4444-555555555555',+ operator: 'lt',+ values: [6],+ },+ })})it('returns null when the tile is not a row-level predicate', () => {@@ -250,17 +262,20 @@ describe('parseTileValues', () => {{id: 'b',label: 'Sum',- metric: { type: 'sum', columnExpression: 'health_score', columnLabel: 'Health score' },+ metric: {+ type: 'sum',+ columnExpression:+ 'toFloatOrNull(accounts.custom_properties.values.`11111111-2222-3333-4444-555555555555`)',+ columnLabel: 'Health score',+ },},]function responseWith(metricsResults: (number | null)[] | undefined): any {return {- kind: NodeKind.AccountsQuery,+ kind: NodeKind.AccountsTableQuery,results: [],- columns: [],- types: [],- hogql: '',+ hasMore: false,limit: 0,offset: 0,metricsResults,diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.tsindex 6f84ee7c8a9c..dc610221d518 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts@@ -2,10 +2,20 @@ import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reduimport posthog from 'posthog-js'import { v4 as uuidv4 } from 'uuid'+import { isUUIDLike } from 'lib/utils/guards'import { objectsEqual } from 'lib/utils/objects'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'-import { AccountsQueryResponse, DataNode } from '~/queries/schema/schema-general'+import {+ AccountsTableAggregation,+ AccountsTableCustomPropertyFilter,+ AccountsTableCustomPropertyOperator,+ AccountsTableMetric,+ AccountsTableQueryResponse,+ AccountsQueryResponse,+ AccountsTableThresholdOperator,+ DataNode,+} from '~/queries/schema/schema-general'import type { CustomPropertyDisplayTypeEnumApi } from 'products/customer_analytics/frontend/generated/api.schemas'@@ -35,9 +45,8 @@ import {NUMERIC_FIELD_TYPES,} from './constants'-// Single-column scalar aggregations whose metric-type name is also the HogQL-// aggregate function name (see tileMetricExpression). They share one shape and-// support an optional `scale` multiplier, e.g. sum(mrr) * 12 to annualize.+// Single-column scalar aggregations share one saved-view shape and support an+// optional scale multiplier, such as annualizing monthly recurring revenue.export const COLUMN_AGGREGATE_TYPES = ['sum', 'avg', 'min', 'max', 'median'] as constexport type ColumnAggregateType = (typeof COLUMN_AGGREGATE_TYPES)[number]@@ -80,13 +89,12 @@ export interface AccountsOverviewTile {export interface TileFilter {tileId: stringexpression: string+ filter?: AccountsTableCustomPropertyFilter}-// Strip a trailing `AS alias` from a HogQL fragment — column entries in the-// account column groups carry aliases (e.g. `accounts.health.score AS score`)-// so the data table can address them by name, but aggregation expressions-// must reference the bare column.-export function stripHogqlAlias(expression: string): string {+// Saved column expressions include an alias for table rendering, while saved+// tile expressions identify the underlying typed custom property.+export function stripColumnAlias(expression: string): string {return expression.replace(/\s+AS\s+[A-Za-z_][\w]*\s*$/i, '').trim()}@@ -94,30 +102,25 @@ export function isNumericColumnType(type: string | undefined): boolean {if (!type) {return false}- // Regular columns carry a HogQL field type; custom-property columns carry a display type.+ // Account fields carry schema types, while custom properties carry display types.return NUMERIC_FIELD_TYPES.has(type) || isNumericDisplayType(type as CustomPropertyDisplayTypeEnumApi)}export function numericColumnOptions(groups: AccountColumnGroup[]): AccountColumnOption[] {- return groups- .filter((group) => !group.isFreeform)- .flatMap((group) =>- group.options- .filter((option) => isNumericColumnType(option.type))- .map((option) => {- const expression = stripHogqlAlias(option.expression)- return {- ...option,- // Custom-property values are stored as coalesced strings; cast so sum/avg aggregate numerically.- expression: group.key === 'custom_properties' ? `toFloatOrNull(${expression})` : expression,- }- })- )+ return groups.flatMap((group) =>+ group.options+ .filter((option) => isNumericColumnType(option.type))+ .map((option) => {+ const expression = stripColumnAlias(option.expression)+ return {+ ...option,+ // Preserve the existing saved-tile expression shape while execution uses a typed metric.+ expression: group.key === 'custom_properties' ? `toFloatOrNull(${expression})` : expression,+ }+ })+ )}-// A `scale` of undefined/1 (or anything non-finite) is a no-op; otherwise the-// aggregation is multiplied by the literal. `scale` is always a finite number-// from the editor's numeric input, so it is safe to inline into the HogQL.export function applyScale(expression: string, scale: number | undefined): string {if (scale === undefined || !Number.isFinite(scale) || scale === 1) {return expression@@ -125,12 +128,6 @@ export function applyScale(expression: string, scale: number | undefined): strinreturn `${expression} * ${scale}`}-// Human-readable multiplier suffix for tile labels/captions (e.g. " × 12").-// Empty when the scale is a no-op, mirroring applyScale's guard.-export function scaleSuffix(scale: number | undefined): string {- return scale === undefined || !Number.isFinite(scale) || scale === 1 ? '' : ` × ${scale}`-}-export function tileMetricExpression(tile: AccountsOverviewTile): string {const { metric } = tileswitch (metric.type) {@@ -139,11 +136,56 @@ export function tileMetricExpression(tile: AccountsOverviewTile): string {case 'count_threshold':return `countIf(${metric.columnExpression} ${metric.operator} ${metric.value})`default:- // sum | avg | min | max | median: the metric type is the HogQL aggregate fn name.return applyScale(`${metric.type}(${metric.columnExpression})`, metric.scale)}}+export function scaleSuffix(scale: number | undefined): string {+ return scale === undefined || !Number.isFinite(scale) || scale === 1 ? '' : ` × ${scale}`+}++const CUSTOM_PROPERTY_METRIC_REGEX = /^(?:toFloatOrNull\()?accounts\.custom_properties\.values\.`([0-9a-fA-F-]+)`\)?$/++function metricDefinitionId(columnExpression: string): string | null {+ const definitionId = stripColumnAlias(columnExpression).match(CUSTOM_PROPERTY_METRIC_REGEX)?.[1]+ return definitionId && isUUIDLike(definitionId) ? definitionId : null+}++export function tileQueryMetric(tile: AccountsOverviewTile): AccountsTableMetric | null {+ if (tile.metric.type === 'count') {+ return { kind: 'count' }+ }+ const definitionId = metricDefinitionId(tile.metric.columnExpression)+ if (!definitionId) {+ return null+ }+ const column = { kind: 'custom_property' as const, definitionId }+ if (tile.metric.type === 'count_threshold') {+ const operator = {+ '>': AccountsTableThresholdOperator.GreaterThan,+ '>=': AccountsTableThresholdOperator.GreaterThanOrEqual,+ '<': AccountsTableThresholdOperator.LessThan,+ '<=': AccountsTableThresholdOperator.LessThanOrEqual,+ '=': AccountsTableThresholdOperator.Equal,+ '!=': AccountsTableThresholdOperator.NotEqual,+ }[tile.metric.operator]+ return operator ? { kind: 'count_threshold', column, operator, value: tile.metric.value } : null+ }+ const aggregation = {+ sum: AccountsTableAggregation.Sum,+ avg: AccountsTableAggregation.Average,+ min: AccountsTableAggregation.Minimum,+ max: AccountsTableAggregation.Maximum,+ median: AccountsTableAggregation.Median,+ }[tile.metric.type]+ return {+ kind: 'aggregate',+ aggregation,+ column,+ scale: Number.isFinite(tile.metric.scale) ? tile.metric.scale : undefined,+ }+}+// The auto-derived subtitle for a tile, from its metric. `count` has none.export function autoCaption(tile: AccountsOverviewTile): string | undefined {const { metric } = tile@@ -165,15 +207,25 @@ export function tileCaption(tile: AccountsOverviewTile): string | undefined {return custom ? custom : autoCaption(tile)}-// A tile only acts as a row-level predicate when it represents an-// inherently row-level condition. `count_threshold` does; `count` and the-// column aggregations describe the whole set, not a subset.-export function tileToRowFilter(tile: AccountsOverviewTile): string | null {- if (tile.metric.type !== 'count_threshold') {+export function tileToRowFilter(tile: AccountsOverviewTile): AccountsTableCustomPropertyFilter | null {+ const metric = tileQueryMetric(tile)+ if (!metric || metric.kind !== 'count_threshold') {return null}- const { columnExpression, operator, value } = tile.metric- return `${columnExpression} ${operator} ${value}`+ const operator = {+ [AccountsTableThresholdOperator.GreaterThan]: AccountsTableCustomPropertyOperator.GreaterThan,+ [AccountsTableThresholdOperator.GreaterThanOrEqual]: AccountsTableCustomPropertyOperator.GreaterThanOrEqual,+ [AccountsTableThresholdOperator.LessThan]: AccountsTableCustomPropertyOperator.LessThan,+ [AccountsTableThresholdOperator.LessThanOrEqual]: AccountsTableCustomPropertyOperator.LessThanOrEqual,+ [AccountsTableThresholdOperator.Equal]: AccountsTableCustomPropertyOperator.Exact,+ [AccountsTableThresholdOperator.NotEqual]: AccountsTableCustomPropertyOperator.IsNot,+ }[metric.operator]+ return {+ kind: 'custom_property',+ definitionId: metric.column.definitionId,+ operator,+ values: [metric.value],+ }}export function isTileClickable(tile: AccountsOverviewTile): boolean {@@ -181,8 +233,14 @@ export function isTileClickable(tile: AccountsOverviewTile): boolean {}export function tileFilterFor(tile: AccountsOverviewTile): TileFilter | null {- const expression = tileToRowFilter(tile)- return expression ? { tileId: tile.id, expression } : null+ if (tile.metric.type !== 'count_threshold') {+ return null+ }+ return {+ tileId: tile.id,+ expression: `${tile.metric.columnExpression} ${tile.metric.operator} ${tile.metric.value}`,+ filter: tileToRowFilter(tile) ?? undefined,+ }}function readNumeric(raw: unknown): number | null {@@ -194,7 +252,7 @@ function readNumeric(raw: unknown): number | null {}export function parseTileValues(- response: AccountsQueryResponse | null,+ response: AccountsQueryResponse | AccountsTableQueryResponse | null,tiles: AccountsOverviewTile[]): Record<string, number | null> {const values: Record<string, number | null> = {}@@ -281,6 +339,7 @@ export interface accountsOverviewTilesLogicValues {metrics: string[]numericColumnExpressions: Set<string>numericColumns: AccountColumnOption[]+ postgresMetrics: AccountsTableMetric[]reconciledTiles: AccountsOverviewTile[]selectedTileId: string | nulltileFilter: TileFilter | null@@ -347,6 +406,7 @@ export interface accountsOverviewTilesLogicMeta {numericColumnExpressions: Set<string>) => AccountsOverviewTile[]metrics: (reconciledTiles: AccountsOverviewTile[]) => string[]+ postgresMetrics: (reconciledTiles: AccountsOverviewTile[]) => AccountsTableMetric[]tileValues: (accountsResponse:| ErrorTrackingQueryResponse@@ -463,10 +523,17 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([(s) => [s.reconciledTiles],(tiles: AccountsOverviewTile[]): string[] => tiles.map(tileMetricExpression),],+ postgresMetrics: [+ (s) => [s.reconciledTiles],+ (tiles: AccountsOverviewTile[]): AccountsTableMetric[] =>+ tiles.map(tileQueryMetric).filter((metric): metric is AccountsTableMetric => metric !== null),+ ],tileValues: [(s) => [s.accountsResponse, s.reconciledTiles],- (response: AccountsQueryResponse | null, tiles: AccountsOverviewTile[]): Record<string, number | null> =>- parseTileValues(response, tiles),+ (+ response: AccountsQueryResponse | AccountsTableQueryResponse | null,+ tiles: AccountsOverviewTile[]+ ): Record<string, number | null> => parseTileValues(response, tiles),],tilesLoading: [(s) => [s.accountsResponseLoading], (loading: boolean): boolean => loading],selectedTileId: [(s) => [s.tileFilter], (filter: TileFilter | null): string | null => filter?.tileId ?? null],diff --git a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.tsindex 04493f811bef..4dadb0dae5e1 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts@@ -135,8 +135,65 @@ describe('accountsTableQuery', () => {expect(plan?.query.filters).toEqual([{ kind: 'account_id', accountId: RELATIONSHIP_ID }])})+ it('translates a threshold tile into a typed list filter', () => {+ const plan = buildAccountsTableQueryPlan(+ queryInput({+ tileFilter: {+ tileId: 'tile',+ expression: `toFloatOrNull(accounts.custom_properties.values.\`${CUSTOM_PROPERTY_ID}\`) > 1`,+ filter: {+ kind: 'custom_property',+ definitionId: CUSTOM_PROPERTY_ID,+ operator: AccountsTableCustomPropertyOperator.GreaterThan,+ values: [1],+ },+ },+ })+ )++ expect(plan?.query.filters).toEqual([+ {+ kind: 'custom_property',+ definitionId: CUSTOM_PROPERTY_ID,+ operator: AccountsTableCustomPropertyOperator.GreaterThan,+ values: [1],+ },+ ])+ })++ it('excludes unset accounts from a not-equal threshold tile', () => {+ const plan = buildAccountsTableQueryPlan(+ queryInput({+ tileFilter: {+ tileId: 'tile',+ expression: `toFloatOrNull(accounts.custom_properties.values.\`${CUSTOM_PROPERTY_ID}\`) != 1`,+ filter: {+ kind: 'custom_property',+ definitionId: CUSTOM_PROPERTY_ID,+ operator: AccountsTableCustomPropertyOperator.IsNot,+ values: [1],+ },+ },+ })+ )++ expect(plan?.query.filters).toEqual([+ {+ kind: 'custom_property',+ definitionId: CUSTOM_PROPERTY_ID,+ operator: AccountsTableCustomPropertyOperator.IsSet,+ values: [],+ },+ {+ kind: 'custom_property',+ definitionId: CUSTOM_PROPERTY_ID,+ operator: AccountsTableCustomPropertyOperator.IsNot,+ values: [1],+ },+ ])+ })+it.each([- ['tile filter', { tileFilter: { tileId: 'tile', expression: 'count > 1' } }],['unsupported column',{ querySelectColumns: ['name', 'arbitrary_hogql()'], visibleColumnNames: ['name', 'x'] },diff --git a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.tsindex 8fdaadd124bb..780ace6a8330 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts@@ -40,8 +40,6 @@ const CUSTOM_PROPERTY_OPERATOR_MAP: Partial<Record<PropertyOperator, AccountsTab[PropertyOperator.IsNot]: AccountsTableCustomPropertyOperator.IsNot,[PropertyOperator.IContains]: AccountsTableCustomPropertyOperator.Contains,[PropertyOperator.NotIContains]: AccountsTableCustomPropertyOperator.DoesNotContain,- [PropertyOperator.Regex]: AccountsTableCustomPropertyOperator.Regex,- [PropertyOperator.NotRegex]: AccountsTableCustomPropertyOperator.NotRegex,[PropertyOperator.GreaterThan]: AccountsTableCustomPropertyOperator.GreaterThan,[PropertyOperator.GreaterThanOrEqual]: AccountsTableCustomPropertyOperator.GreaterThanOrEqual,[PropertyOperator.LessThan]: AccountsTableCustomPropertyOperator.LessThan,@@ -88,7 +86,7 @@ function accountFieldFromExpression(expression: string): AccountsTableAccountFiereturn jsonField && ACCOUNT_FIELD_VALUES.has(jsonField) ? (jsonField as AccountsTableAccountField) : null}-function columnFromExpression(+export function columnFromExpression(expression: string,columnDisplay: AccountColumnDisplayState): AccountsTableColumn | null {@@ -135,12 +133,6 @@ function customPropertyFilter(if (!definition || !operator) {return null}- if (- operator === AccountsTableCustomPropertyOperator.Regex ||- operator === AccountsTableCustomPropertyOperator.NotRegex- ) {- return null- }if ((operator === AccountsTableCustomPropertyOperator.Contains ||operator === AccountsTableCustomPropertyOperator.DoesNotContain) &&@@ -212,6 +204,25 @@ function queryFilters(input: BuildAccountsTableQueryPlanInput): AccountsTableFil}filters.push(translatedFilter)}+ if (input.tileFilter) {+ const filter = input.tileFilter.filter+ if (!filter) {+ return null+ }+ const definition = input.customPropertyDefinitionsById[filter.definitionId]+ if (!isUUIDLike(filter.definitionId) || !definition || !isNumericDisplayType(definition.display_type)) {+ return null+ }+ if (filter.operator === AccountsTableCustomPropertyOperator.IsNot) {+ filters.push({+ kind: 'custom_property',+ definitionId: filter.definitionId,+ operator: AccountsTableCustomPropertyOperator.IsSet,+ values: [],+ })+ }+ filters.push(filter)+ }return filters}@@ -223,7 +234,7 @@ function sortableColumn(column: AccountsTableColumn): AccountsTableSortableColum}export function buildAccountsTableQueryPlan(input: BuildAccountsTableQueryPlanInput): AccountsTableQueryPlan | null {- if (input.tileFilter || input.querySelectColumns.length !== input.visibleColumnNames.length) {+ if (input.querySelectColumns.length !== input.visibleColumnNames.length) {return null}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.tsindex b68efb69ce6e..2620a1e7ccb1 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewState.test.ts@@ -1,7 +1,9 @@+import { AccountsTableCustomPropertyOperator } from '~/queries/schema/schema-general'import { PropertyFilterType, PropertyOperator } from '~/types'import { ACCOUNTS_HOGQL_DEFAULT_SELECT } from './accountsColumnConfigLogic'import {+ AccountsViewState,deserializeAccountsView,normalizeRoleFilter,orderByToSortOrder,@@ -49,7 +51,7 @@ describe('normalizeRoleFilter', () => {describe('serializeAccountsView / deserializeAccountsView', () => {it('round-trips a fully populated view', () => {- const state = {+ const state: AccountsViewState = {columns: ['name', 'csm'],sortOrder: { column: 'csm' as const, direction: 'desc' as const },filters: {@@ -57,7 +59,16 @@ describe('serializeAccountsView / deserializeAccountsView', () => {tags: ['enterprise'],unassigned: false,assignedTo: [1, 2, 3],- tileFilter: { tileId: 't1', expression: 'mrr > 100' },+ tileFilter: {+ tileId: 't1',+ expression: 'mrr > 100',+ filter: {+ kind: 'custom_property',+ definitionId: '11111111-2222-3333-4444-555555555555',+ operator: AccountsTableCustomPropertyOperator.GreaterThan,+ values: [100],+ },+ },customProperties: [{type: PropertyFilterType.AccountCustomProperty as const,diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.tsindex 0523335b2f0d..72e0ae35655d 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts@@ -2,12 +2,10 @@ import { MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from '~/lib/api.mock'import { expectLogic } from 'kea-test-utils'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { userLogic } from 'scenes/userLogic'import { useMocks } from '~/mocks/jest'-import type { AccountsTableQuery } from '~/queries/schema/schema-general'+import { AccountsTableCustomPropertyOperator } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { ColumnConfigurationApi } from 'products/product_analytics/frontend/generated/api.schemas'@@ -82,7 +80,16 @@ describe('accountsViewsLogic', () => {tags: ['enterprise'],unassigned: false,assignedTo: [1, 2, 3],- tileFilter: { tileId: 't1', expression: 'mrr > 100' },+ tileFilter: {+ tileId: 't1',+ expression: 'mrr > 100',+ filter: {+ kind: 'custom_property',+ definitionId: '11111111-2222-3333-4444-555555555555',+ operator: AccountsTableCustomPropertyOperator.GreaterThan,+ values: [100],+ },+ },},})await expectLogic(logic, () => logic.actions.applyView(view)).toFinishAllListeners()@@ -96,34 +103,17 @@ describe('accountsViewsLogic', () => {expect(accountsOverviewTilesLogic.values.tiles).toEqual([{ id: 't1', label: 'Accounts', metric: { type: 'count' } },])- expect(accountsOverviewTilesLogic.values.tileFilter).toEqual({ tileId: 't1', expression: 'mrr > 100' })- expect(logic.values.currentViewId).toEqual('view-1')- })-- it('translates an applied saved view into the Postgres query', async () => {- useMocks({ get: { '/api/environments/:team_id/column_configurations/': { count: 0, results: [] } } })- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES], {- [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNTS_POSTGRES]: true,+ expect(accountsOverviewTilesLogic.values.tileFilter).toEqual({+ tileId: 't1',+ expression: 'mrr > 100',+ filter: {+ kind: 'custom_property',+ definitionId: '11111111-2222-3333-4444-555555555555',+ operator: AccountsTableCustomPropertyOperator.GreaterThan,+ values: [100],+ },})- mountAll()- await expectLogic(logic, () =>- logic.actions.applyView(- buildView({- columns: ['name'],- filters: { search: 'acme', tags: ['enterprise'], assignedTo: [1, 2] },- order_by: ['name DESC'],- })- )- ).toFinishAllListeners()-- const source = accountsLogic.values.accountsQuerySource as AccountsTableQuery- expect(source.kind).toBe('AccountsTableQuery')- expect(source.columns).toEqual([{ kind: 'account_field', field: 'name' }])- expect(source.filters).toEqual([- { kind: 'search', query: 'acme' },- { kind: 'tags', tagNames: ['enterprise'] },- { kind: 'assigned_to', userIds: [1, 2] },- ])+ expect(logic.values.currentViewId).toEqual('view-1')})it('isDirty flips when live state diverges from the applied view and clears on re-apply', async () => {diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex c13144bfcc44..9fdd0c4fb2f3 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -5172,6 +5172,8 @@ export interface Response23Api {hogql?: string | nullkind?: 'AccountsTableQuery'limit: number+ /** Aggregated values in the same order as the requested metrics. */+ metricsResults?: (number | null)[] | null/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiersApi | nulloffset: number@@ -8099,6 +8101,47 @@ export interface AccountsTableCustomPropertyFilterApi {values?: (string | number | boolean)[] | null}+export const AccountsTableCountMetricApiValue = {+ kind: 'count',+} as const+export type AccountsTableCountMetricApi = typeof AccountsTableCountMetricApiValue++export type AccountsTableAggregationApi = (typeof AccountsTableAggregationApi)[keyof typeof AccountsTableAggregationApi]++export const AccountsTableAggregationApi = {+ Sum: 'sum',+ Avg: 'avg',+ Min: 'min',+ Max: 'max',+ Median: 'median',+} as const++export interface AccountsTableAggregateMetricApi {+ aggregation: AccountsTableAggregationApi+ column: AccountsTableCustomPropertyColumnApi+ kind?: 'aggregate'+ scale?: number | null+}++export type AccountsTableThresholdOperatorApi =+ (typeof AccountsTableThresholdOperatorApi)[keyof typeof AccountsTableThresholdOperatorApi]++export const AccountsTableThresholdOperatorApi = {+ Gt: 'gt',+ Gte: 'gte',+ Lt: 'lt',+ Lte: 'lte',+ Exact: 'exact',+ IsNot: 'is_not',+} as const++export interface AccountsTableCountThresholdMetricApi {+ column: AccountsTableCustomPropertyColumnApi+ kind?: 'count_threshold'+ operator: AccountsTableThresholdOperatorApi+ value: number+}+export interface AccountsTableQueryResponseApi {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null@@ -8107,6 +8150,8 @@ export interface AccountsTableQueryResponseApi {hogql?: string | nullkind?: 'AccountsTableQuery'limit: number+ /** Aggregated values in the same order as the requested metrics. */+ metricsResults?: (number | null)[] | null/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiersApi | nulloffset: number@@ -8167,6 +8212,10 @@ export interface AccountsTableQueryApi {| nullkind?: 'AccountsTableQuery'limit?: number | null+ /** Aggregates to evaluate against the filtered account set. A metrics query skips row loading. */+ metrics?:+ | (AccountsTableCountMetricApi | AccountsTableAggregateMetricApi | AccountsTableCountThresholdMetricApi)[]+ | null/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiersApi | nulloffset?: number | nulldiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex ca6bdc664c5f..186a5ac5e58d 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -4431,6 +4431,8 @@ export interface Response23Api {hogql?: string | nullkind?: 'AccountsTableQuery'limit: number+ /** Aggregated values in the same order as the requested metrics. */+ metricsResults?: (number | null)[] | null/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiersApi | nulloffset: number@@ -7358,6 +7360,47 @@ export interface AccountsTableCustomPropertyFilterApi {values?: (string | number | boolean)[] | null}+export const AccountsTableCountMetricApiValue = {+ kind: 'count',+} as const+export type AccountsTableCountMetricApi = typeof AccountsTableCountMetricApiValue++export type AccountsTableAggregationApi = (typeof AccountsTableAggregationApi)[keyof typeof AccountsTableAggregationApi]++export const AccountsTableAggregationApi = {+ Sum: 'sum',+ Avg: 'avg',+ Min: 'min',+ Max: 'max',+ Median: 'median',+} as const++export interface AccountsTableAggregateMetricApi {+ aggregation: AccountsTableAggregationApi+ column: AccountsTableCustomPropertyColumnApi+ kind?: 'aggregate'+ scale?: number | null+}++export type AccountsTableThresholdOperatorApi =+ (typeof AccountsTableThresholdOperatorApi)[keyof typeof AccountsTableThresholdOperatorApi]++export const AccountsTableThresholdOperatorApi = {+ Gt: 'gt',+ Gte: 'gte',+ Lt: 'lt',+ Lte: 'lte',+ Exact: 'exact',+ IsNot: 'is_not',+} as const++export interface AccountsTableCountThresholdMetricApi {+ column: AccountsTableCustomPropertyColumnApi+ kind?: 'count_threshold'+ operator: AccountsTableThresholdOperatorApi+ value: number+}+export interface AccountsTableQueryResponseApi {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null@@ -7366,6 +7409,8 @@ export interface AccountsTableQueryResponseApi {hogql?: string | nullkind?: 'AccountsTableQuery'limit: number+ /** Aggregated values in the same order as the requested metrics. */+ metricsResults?: (number | null)[] | null/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiersApi | nulloffset: number@@ -7426,6 +7471,10 @@ export interface AccountsTableQueryApi {| nullkind?: 'AccountsTableQuery'limit?: number | null+ /** Aggregates to evaluate against the filtered account set. A metrics query skips row loading. */+ metrics?:+ | (AccountsTableCountMetricApi | AccountsTableAggregateMetricApi | AccountsTableCountThresholdMetricApi)[]+ | null/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiersApi | nulloffset?: number | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c82c9fa31ce2..8907b19f10b1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -851,16 +851,58 @@ export namespace Schemas {kind?: 'account_id';}+ export type AccountsTableAggregation = typeof AccountsTableAggregation[keyof typeof AccountsTableAggregation];+++ export const AccountsTableAggregation = {+ Sum: 'sum',+ Avg: 'avg',+ Min: 'min',+ Max: 'max',+ Median: 'median',+ } as const;++ export interface AccountsTableCustomPropertyColumn {+ /** Team-scoped custom property definition to return for each account. */+ definitionId: string;+ kind?: 'custom_property';+ }++ export interface AccountsTableAggregateMetric {+ aggregation: AccountsTableAggregation;+ column: AccountsTableCustomPropertyColumn;+ kind?: 'aggregate';+ scale?: number | null;+ }+export interface AccountsTableAssignedToFilter {kind?: 'assigned_to';/** Match accounts where any listed user actively holds any relationship. */userIds: number[];}- export interface AccountsTableCustomPropertyColumn {- /** Team-scoped custom property definition to return for each account. */- definitionId: string;- kind?: 'custom_property';+ export const AccountsTableCountMetricValue = {+ kind: 'count',+ } as const;+ export type AccountsTableCountMetric = typeof AccountsTableCountMetricValue;++ export type AccountsTableThresholdOperator = typeof AccountsTableThresholdOperator[keyof typeof AccountsTableThresholdOperator];+++ export const AccountsTableThresholdOperator = {+ Gt: 'gt',+ Gte: 'gte',+ Lt: 'lt',+ Lte: 'lte',+ Exact: 'exact',+ IsNot: 'is_not',+ } as const;++ export interface AccountsTableCountThresholdMetric {+ column: AccountsTableCustomPropertyColumn;+ kind?: 'count_threshold';+ operator: AccountsTableThresholdOperator;+ value: number;}export type AccountsTableCustomPropertyOperator = typeof AccountsTableCustomPropertyOperator[keyof typeof AccountsTableCustomPropertyOperator];@@ -993,6 +1035,8 @@ export namespace Schemas {hogql?: string | null;kind?: 'AccountsTableQuery';limit: number;+ /** Aggregated values in the same order as the requested metrics. */+ metricsResults?: (number | null)[] | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;offset: number;@@ -1032,6 +1076,8 @@ export namespace Schemas {filters?: (AccountsTableSearchFilter | AccountsTableTagsFilter | AccountsTableAssignedToFilter | AccountsTableUnassignedFilter | AccountsTableAccountIdFilter | AccountsTableCustomPropertyFilter)[] | null;kind?: 'AccountsTableQuery';limit?: number | null;+ /** Aggregates to evaluate against the filtered account set. A metrics query skips row loading. */+ metrics?: (AccountsTableCountMetric | AccountsTableAggregateMetric | AccountsTableCountThresholdMetric)[] | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;offset?: number | null;@@ -6455,6 +6501,8 @@ export namespace Schemas {hogql?: string | null;kind?: 'AccountsTableQuery';limit: number;+ /** Aggregated values in the same order as the requested metrics. */+ metricsResults?: (number | null)[] | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;offset: number;@@ -65285,6 +65333,8 @@ export namespace Schemas {hogql?: string | null;kind?: 'AccountsTableQuery';limit: number;+ /** Aggregated values in the same order as the requested metrics. */+ metricsResults?: (number | null)[] | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;offset: number;@@ -65898,6 +65948,8 @@ export namespace Schemas {hogql?: string | null;kind?: 'AccountsTableQuery';limit: number;+ /** Aggregated values in the same order as the requested metrics. */+ metricsResults?: (number | null)[] | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;offset: number;