: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 table filters and sorting (#79991)
Arthur Moreira de Deuse555a81d53e4
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 91fee7190fdd..e1a6380cf669 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -267,6 +267,38 @@"required": ["kind", "field"],"type": "object"},+ "AccountsTableAccountIdFilter": {+ "additionalProperties": false,+ "properties": {+ "accountId": {+ "type": "string"+ },+ "kind": {+ "const": "account_id",+ "type": "string"+ }+ },+ "required": ["kind", "accountId"],+ "type": "object"+ },+ "AccountsTableAssignedToFilter": {+ "additionalProperties": false,+ "properties": {+ "kind": {+ "const": "assigned_to",+ "type": "string"+ },+ "userIds": {+ "description": "Match accounts where any listed user actively holds any relationship.",+ "items": {+ "$ref": "#/definitions/integer"+ },+ "type": "array"+ }+ },+ "required": ["kind", "userIds"],+ "type": "object"+ },"AccountsTableColumn": {"description": "A typed column supported by the Postgres-backed Accounts table.","discriminator": {@@ -310,6 +342,30 @@"required": ["kind", "definitionId"],"type": "object"},+ "AccountsTableCustomPropertyFilter": {+ "additionalProperties": false,+ "properties": {+ "definitionId": {+ "type": "string"+ },+ "kind": {+ "const": "custom_property",+ "type": "string"+ },+ "operator": {+ "$ref": "#/definitions/AccountsTableCustomPropertyOperator"+ },+ "values": {+ "description": "Values interpreted according to the custom property definition's display type.",+ "items": {+ "type": ["string", "number", "boolean"]+ },+ "type": "array"+ }+ },+ "required": ["kind", "definitionId", "operator"],+ "type": "object"+ },"AccountsTableCustomPropertyHistoryColumn": {"additionalProperties": false,"properties": {@@ -344,9 +400,57 @@"required": ["timestamp", "value"],"type": "object"},+ "AccountsTableCustomPropertyOperator": {+ "enum": [+ "exact",+ "is_not",+ "icontains",+ "not_icontains",+ "regex",+ "not_regex",+ "gt",+ "gte",+ "lt",+ "lte",+ "is_set",+ "is_not_set",+ "is_date_exact",+ "is_date_before",+ "is_date_after"+ ],+ "type": "string"+ },"AccountsTableCustomPropertyValue": {"type": ["string", "number", "boolean", "null"]},+ "AccountsTableFilter": {+ "description": "A typed filter applied to the Postgres-backed Accounts table.",+ "discriminator": {+ "propertyName": "kind"+ },+ "oneOf": [+ {+ "$ref": "#/definitions/AccountsTableSearchFilter"+ },+ {+ "$ref": "#/definitions/AccountsTableTagsFilter"+ },+ {+ "$ref": "#/definitions/AccountsTableAssignedToFilter"+ },+ {+ "$ref": "#/definitions/AccountsTableUnassignedFilter"+ },+ {+ "$ref": "#/definitions/AccountsTableAccountIdFilter"+ },+ {+ "$ref": "#/definitions/AccountsTableCustomPropertyFilter"+ }+ ],+ "required": ["kind"],+ "type": "object"+ },"AccountsTableNoteCountColumn": {"additionalProperties": false,"properties": {@@ -368,6 +472,13 @@},"type": "array"},+ "filters": {+ "description": "Filters are combined with AND. Values within tag and assignment filters use OR.",+ "items": {+ "$ref": "#/definitions/AccountsTableFilter"+ },+ "type": "array"+ },"kind": {"const": "AccountsTableQuery","type": "string"@@ -385,6 +496,9 @@"response": {"$ref": "#/definitions/AccountsTableQueryResponse"},+ "sort": {+ "$ref": "#/definitions/AccountsTableSort"+ },"tags": {"$ref": "#/definitions/QueryLogTags"},@@ -550,6 +664,62 @@"required": ["id", "name", "accountFields", "relationships", "customProperties", "customPropertyHistory"],"type": "object"},+ "AccountsTableSearchFilter": {+ "additionalProperties": false,+ "properties": {+ "kind": {+ "const": "search",+ "type": "string"+ },+ "query": {+ "type": "string"+ }+ },+ "required": ["kind", "query"],+ "type": "object"+ },+ "AccountsTableSort": {+ "additionalProperties": false,+ "properties": {+ "column": {+ "$ref": "#/definitions/AccountsTableSortableColumn"+ },+ "direction": {+ "$ref": "#/definitions/AccountsTableSortDirection"+ }+ },+ "required": ["column", "direction"],+ "type": "object"+ },+ "AccountsTableSortDirection": {+ "enum": ["asc", "desc"],+ "type": "string"+ },+ "AccountsTableSortableColumn": {+ "description": "A typed column that supports server-side sorting.",+ "discriminator": {+ "propertyName": "kind"+ },+ "oneOf": [+ {+ "$ref": "#/definitions/AccountsTableAccountFieldColumn"+ },+ {+ "$ref": "#/definitions/AccountsTableTagsColumn"+ },+ {+ "$ref": "#/definitions/AccountsTableNoteCountColumn"+ },+ {+ "$ref": "#/definitions/AccountsTableRelationshipColumn"+ },+ {+ "$ref": "#/definitions/AccountsTableCustomPropertyColumn"+ }+ ],+ "required": ["kind"],+ "type": "object"+ },"AccountsTableTagsColumn": {"additionalProperties": false,"properties": {@@ -561,6 +731,35 @@"required": ["kind"],"type": "object"},+ "AccountsTableTagsFilter": {+ "additionalProperties": false,+ "properties": {+ "kind": {+ "const": "tags",+ "type": "string"+ },+ "tagNames": {+ "description": "Match accounts carrying any of these tag names.",+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["kind", "tagNames"],+ "type": "object"+ },+ "AccountsTableUnassignedFilter": {+ "additionalProperties": false,+ "properties": {+ "kind": {+ "const": "unassigned",+ "type": "string"+ }+ },+ "required": ["kind"],+ "type": "object"+ },"ActionConversionGoal": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 3056dfa475fa..ce4d3c90bb3b 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -2819,6 +2819,91 @@ export type AccountsTableColumn =| AccountsTableCustomPropertyColumn| AccountsTableCustomPropertyHistoryColumn+/**+ * A typed column that supports server-side sorting.+ * @discriminator kind+ */+export type AccountsTableSortableColumn =+ | AccountsTableAccountFieldColumn+ | AccountsTableTagsColumn+ | AccountsTableNoteCountColumn+ | AccountsTableRelationshipColumn+ | AccountsTableCustomPropertyColumn++export enum AccountsTableSortDirection {+ Ascending = 'asc',+ Descending = 'desc',+}++export interface AccountsTableSort {+ column: AccountsTableSortableColumn+ direction: AccountsTableSortDirection+}++export interface AccountsTableSearchFilter {+ kind: 'search'+ query: string+}++export interface AccountsTableTagsFilter {+ kind: 'tags'+ /** Match accounts carrying any of these tag names. */+ tagNames: string[]+}++export interface AccountsTableAssignedToFilter {+ kind: 'assigned_to'+ /** Match accounts where any listed user actively holds any relationship. */+ userIds: integer[]+}++export interface AccountsTableUnassignedFilter {+ kind: 'unassigned'+}++export interface AccountsTableAccountIdFilter {+ kind: 'account_id'+ accountId: string+}++export enum AccountsTableCustomPropertyOperator {+ Exact = 'exact',+ IsNot = 'is_not',+ Contains = 'icontains',+ DoesNotContain = 'not_icontains',+ Regex = 'regex',+ NotRegex = 'not_regex',+ GreaterThan = 'gt',+ GreaterThanOrEqual = 'gte',+ LessThan = 'lt',+ LessThanOrEqual = 'lte',+ IsSet = 'is_set',+ IsNotSet = 'is_not_set',+ DateExact = 'is_date_exact',+ DateBefore = 'is_date_before',+ DateAfter = 'is_date_after',+}++export interface AccountsTableCustomPropertyFilter {+ kind: 'custom_property'+ definitionId: string+ operator: AccountsTableCustomPropertyOperator+ /** Values interpreted according to the custom property definition's display type. */+ values?: (string | number | boolean)[]+}++/**+ * A typed filter applied to the Postgres-backed Accounts table.+ * @discriminator kind+ */+export type AccountsTableFilter =+ | AccountsTableSearchFilter+ | AccountsTableTagsFilter+ | AccountsTableAssignedToFilter+ | AccountsTableUnassignedFilter+ | AccountsTableAccountIdFilter+ | AccountsTableCustomPropertyFilter+export type AccountsTableCustomPropertyValue = string | number | boolean | nullexport interface AccountsTableCustomPropertyHistoryPoint {@@ -2859,6 +2944,9 @@ export interface AccountsTableQuery extends DataNode<AccountsTableQueryResponse>kind: NodeKind.AccountsTableQuery/** Columns to load for each account. Account identity fields are always returned. */columns: AccountsTableColumn[]+ /** Filters are combined with AND. Values within tag and assignment filters use OR. */+ filters?: AccountsTableFilter[]+ sort?: AccountsTableSortlimit?: positive_integeroffset?: integer}diff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.pyindex 48dc285cc799..65ed1a06accd 100644--- a/posthog/hogql_queries/test/test_access_controlled_resources.py+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py@@ -118,7 +118,7 @@ class TestQueriedAccessControlledResources(BaseTest):assert queried_access_controlled_resources(query, self.team) == set()def test_accounts_table_query_partitions_on_account_access(self):- assert queried_access_controlled_resources(AccountsTableQuery(columns=[]), self.team) == {"account"}+ assert queried_access_controlled_resources(AccountsTableQuery(columns=[], filters=[]), self.team) == {"account"}def test_structured_query_with_data_warehouse_series(self):query = TrendsQuery(series=[EventsNode(event="$pageview"), self._dw_node()])diff --git a/posthog/schema.py b/posthog/schema.pyindex c0349b38aba2..14aefbe4a6e7 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -14,6 +14,8 @@ from posthog.schema_discriminators import property_filter_discriminatorfrom posthog.schema_enums import (AccessControlLevel as AccessControlLevel,AccountsTableAccountField as AccountsTableAccountField,+ AccountsTableCustomPropertyOperator as AccountsTableCustomPropertyOperator,+ AccountsTableSortDirection as AccountsTableSortDirection,Action as Action,AgentMode as AgentMode,AggregationAxisFormat as AggregationAxisFormat,@@ -330,6 +332,14 @@ class AccountsTableAccountFieldColumn(BaseModel):kind: Literal["account_field"] = "account_field"+class AccountsTableAccountIdFilter(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ accountId: str+ kind: Literal["account_id"] = "account_id"++class AccountsTableCustomPropertyColumn(BaseModel):model_config = ConfigDict(extra="forbid",@@ -382,6 +392,14 @@ class AccountsTableRelationshipColumn(BaseModel):kind: Literal["relationship"] = "relationship"+class AccountsTableSearchFilter(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ kind: Literal["search"] = "search"+ query: str++class AccountsTableTagsColumn(BaseModel):model_config = ConfigDict(extra="forbid",@@ -389,6 +407,21 @@ class AccountsTableTagsColumn(BaseModel):kind: Literal["tags"] = "tags"+class AccountsTableTagsFilter(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ kind: Literal["tags"] = "tags"+ tagNames: list[str] = Field(..., description="Match accounts carrying any of these tag names.")+++class AccountsTableUnassignedFilter(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ kind: Literal["unassigned"] = "unassigned"++class AlertScheduleRestrictionWindow(BaseModel):model_config = ConfigDict(extra="forbid",@@ -3045,6 +3078,30 @@ class AccountCustomPropertyFilter(BaseModel):value: list[str | float | bool] | str | float | bool | None = None+class AccountsTableAssignedToFilter(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ kind: Literal["assigned_to"] = "assigned_to"+ userIds: list[int] = Field(+ ...,+ description=("Match accounts where any listed user actively holds any relationship."),+ )+++class AccountsTableCustomPropertyFilter(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ definitionId: str+ kind: Literal["custom_property"] = "custom_property"+ operator: AccountsTableCustomPropertyOperator+ values: list[str | float | bool] | None = Field(+ default=None,+ description=("Values interpreted according to the custom property definition's display type."),+ )++class AccountsTableRow(BaseModel):model_config = ConfigDict(extra="forbid",@@ -8649,6 +8706,24 @@ class AccountsTableQueryResponse(BaseModel):)+class AccountsTableSort(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ column: (+ AccountsTableAccountFieldColumn+ | AccountsTableTagsColumn+ | AccountsTableNoteCountColumn+ | AccountsTableRelationshipColumn+ | AccountsTableCustomPropertyColumn+ ) = Field(+ ...,+ description="A typed column that supports server-side sorting.",+ discriminator="kind",+ )+ direction: AccountsTableSortDirection++class ActorsPropertyTaxonomyQueryResponse(BaseModel):model_config = ConfigDict(extra="forbid",@@ -24154,11 +24229,26 @@ class AccountsTableQuery(BaseModel):...,description=("Columns to load for each account. Account identity fields are always returned."),)+ filters: (+ list[+ AccountsTableSearchFilter+ | AccountsTableTagsFilter+ | AccountsTableAssignedToFilter+ | AccountsTableUnassignedFilter+ | AccountsTableAccountIdFilter+ | AccountsTableCustomPropertyFilter+ ]+ | None+ ) = Field(+ default=None,+ description=("Filters are combined with AND. Values within tag and assignment filters use OR."),+ )kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"limit: conint(ge=1) | None = Nonemodifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")offset: int | None = Noneresponse: AccountsTableQueryResponse | None = None+ sort: AccountsTableSort | None = Nonetags: QueryLogTags | None = Noneversion: float | None = Field(default=None, description="version of the node, used for schema migrations")diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 98aacab3388f..f8911570550f 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -49,6 +49,29 @@ class WindowDays(float, Enum):NUMBER_90 = 90+class AccountsTableCustomPropertyOperator(StrEnum):+ EXACT = "exact"+ IS_NOT = "is_not"+ ICONTAINS = "icontains"+ NOT_ICONTAINS = "not_icontains"+ REGEX = "regex"+ NOT_REGEX = "not_regex"+ GT = "gt"+ GTE = "gte"+ LT = "lt"+ LTE = "lte"+ IS_SET = "is_set"+ IS_NOT_SET = "is_not_set"+ IS_DATE_EXACT = "is_date_exact"+ IS_DATE_BEFORE = "is_date_before"+ IS_DATE_AFTER = "is_date_after"+++class AccountsTableSortDirection(StrEnum):+ ASC = "asc"+ DESC = "desc"++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 756fa66fc91d..4f8cc2d519f7 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -17,17 +17,39 @@ Do NOT:import asynciofrom collections.abc import Iterable-from datetime import datetime, timedelta+from datetime import UTC, datetime, time, timedeltafrom enum import Enumfrom typing import TYPE_CHECKING, Any, Optional, castfrom uuid import UUIDfrom django.apps import appsfrom django.conf import settings+from django.contrib.postgres.aggregates import ArrayAgg+from django.contrib.postgres.fields import ArrayFieldfrom django.core.exceptions import ValidationErrorfrom django.db import IntegrityError, transaction-from django.db.models import CharField, Count, Exists, OuterRef, Prefetch, Q+from django.db.models import (+ BooleanField,+ CharField,+ Count,+ DateTimeField,+ Exists,+ F,+ Field,+ FloatField,+ IntegerField,+ OuterRef,+ Prefetch,+ Q,+ QuerySet,+ Subquery,+ TextField,+ Value,+)+from django.db.models.fields.json import KeyTextTransform+from django.db.models.functions import Coalescefrom django.utils import timezone+from django.utils.dateparse import parse_date, parse_datetimeimport structlogfrom celery import current_app@@ -2119,9 +2141,17 @@ def _account_table_field_values(def _validate_account_table_definitions(- *, team_id: int, selection: contracts.AccountTableColumnSelection+ *,+ team_id: int,+ selection: contracts.AccountTableColumnSelection,+ filters: tuple[contracts.AccountTableFilter, ...],+ sort: contracts.AccountTableSort | None,) -> dict[UUID, DisplayType]:- relationship_ids = selection.relationship_definition_ids+ relationship_ids = set(selection.relationship_definition_ids)+ if sort and sort.kind == contracts.AccountTableSortKind.RELATIONSHIP:+ if sort.definition_id is None:+ raise InvalidAccountTableColumn("Relationship sorting requires a definition.")+ relationship_ids.add(sort.definition_id)if relationship_ids:valid_relationship_ids = set(AccountRelationshipDefinition.objects.for_team(team_id)@@ -2133,9 +2163,14 @@ def _validate_account_table_definitions(invalid_ids = ", ".join(sorted(str(definition_id) for definition_id in invalid_relationship_ids))raise InvalidAccountTableColumn(f"Unknown relationship definitions: {invalid_ids}")- custom_property_ids = selection.custom_property_definition_ids | frozenset(- selection.custom_property_history_windows+ custom_property_ids = set(selection.custom_property_definition_ids) | set(selection.custom_property_history_windows)+ custom_property_ids.update(+ filter_.definition_id for filter_ in filters if isinstance(filter_, contracts.AccountTableCustomPropertyFilter))+ if sort and sort.kind == contracts.AccountTableSortKind.CUSTOM_PROPERTY:+ if sort.definition_id is None:+ raise InvalidAccountTableColumn("Custom property sorting requires a definition.")+ custom_property_ids.add(sort.definition_id)if not custom_property_ids:return {}@@ -2153,7 +2188,7 @@ def _validate_account_table_definitions(non_numeric_history_ids = {definition_idfor definition_id in selection.custom_property_history_windows- if custom_property_display_types[definition_id] not in NUMERIC_DISPLAY_TYPES+ if custom_property_display_types[definition_id].value not in NUMERIC_DISPLAY_TYPES}if non_numeric_history_ids:invalid_ids = ", ".join(sorted(str(definition_id) for definition_id in non_numeric_history_ids))@@ -2161,17 +2196,297 @@ def _validate_account_table_definitions(return custom_property_display_types+def _coerce_datetime_filter_value(value: float | bool | str) -> datetime:+ if not isinstance(value, str):+ raise InvalidAccountTableColumn("Date custom property filters require ISO-8601 values.")+ parsed_datetime = parse_datetime(value)+ if parsed_datetime is None:+ parsed_date = parse_date(value)+ if parsed_date is None:+ raise InvalidAccountTableColumn("Date custom property filters require ISO-8601 values.")+ parsed_datetime = datetime.combine(parsed_date, time.min, tzinfo=UTC)+ elif timezone.is_naive(parsed_datetime):+ parsed_datetime = timezone.make_aware(parsed_datetime, UTC)+ return parsed_datetime+++def _coerce_custom_property_filter_values(+ filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType+) -> tuple[float | bool | str | datetime, ...]:+ data_type = DATA_TYPE_BY_DISPLAY_TYPE[display_type]+ values = filter_.values+ if filter_.operator in {+ contracts.AccountTableCustomPropertyOperator.IS_SET,+ contracts.AccountTableCustomPropertyOperator.IS_NOT_SET,+ }:+ return ()+ if not values:+ raise InvalidAccountTableColumn("Custom property filters require at least one value.")++ if data_type == DataType.NUMERIC:+ if any(isinstance(value, bool) for value in values):+ raise InvalidAccountTableColumn("Numeric custom property filters require numeric values.")+ try:+ return tuple(float(value) for value in values)+ except (TypeError, ValueError) as error:+ raise InvalidAccountTableColumn("Numeric custom property filters require numeric values.") from error+ if data_type == DataType.BOOLEAN:+ coerced: list[bool] = []+ for value in values:+ if isinstance(value, bool):+ coerced.append(value)+ elif str(value).lower() in {"true", "1"}:+ coerced.append(True)+ elif str(value).lower() in {"false", "0"}:+ coerced.append(False)+ else:+ raise InvalidAccountTableColumn("Boolean custom property filters require true or false values.")+ return tuple(coerced)+ if data_type == DataType.DATETIME:+ return tuple(_coerce_datetime_filter_value(value) for value in values)+ return tuple(str(value) for value in values)+++def _custom_property_filter_predicate(+ filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType+) -> tuple[Q, bool]:+ operator = filter_.operator+ data_type = DATA_TYPE_BY_DISPLAY_TYPE[display_type]+ values = _coerce_custom_property_filter_values(filter_, display_type)+ value_field = {+ DataType.STRING: "value_str",+ DataType.NUMERIC: "value_num",+ DataType.BOOLEAN: "value_bool",+ DataType.DATETIME: "value_datetime",+ }[data_type]++ if operator == contracts.AccountTableCustomPropertyOperator.IS_SET:+ return Q(), False+ if operator == contracts.AccountTableCustomPropertyOperator.IS_NOT_SET:+ return Q(), True+ if operator in {+ contracts.AccountTableCustomPropertyOperator.EXACT,+ contracts.AccountTableCustomPropertyOperator.IS_NOT,+ }:+ return Q(**{f"{value_field}__in": values}), operator == contracts.AccountTableCustomPropertyOperator.IS_NOT+ if operator in {+ contracts.AccountTableCustomPropertyOperator.REGEX,+ contracts.AccountTableCustomPropertyOperator.NOT_REGEX,+ }:+ raise InvalidAccountTableColumn("Regex custom property filters are not supported by account table queries.")+ if operator in {+ contracts.AccountTableCustomPropertyOperator.CONTAINS,+ contracts.AccountTableCustomPropertyOperator.DOES_NOT_CONTAIN,+ }:+ if data_type != DataType.STRING:+ raise InvalidAccountTableColumn("Contains operators require a text custom property.")+ predicate = Q()+ for value in values:+ predicate |= Q(value_str__icontains=value)+ return predicate, operator == contracts.AccountTableCustomPropertyOperator.DOES_NOT_CONTAIN+ if operator in {+ contracts.AccountTableCustomPropertyOperator.GREATER_THAN,+ contracts.AccountTableCustomPropertyOperator.GREATER_THAN_OR_EQUAL,+ contracts.AccountTableCustomPropertyOperator.LESS_THAN,+ contracts.AccountTableCustomPropertyOperator.LESS_THAN_OR_EQUAL,+ }:+ if data_type != DataType.NUMERIC:+ raise InvalidAccountTableColumn("Comparison operators require a numeric custom property.")+ if len(values) != 1:+ raise InvalidAccountTableColumn("Numeric comparison filters require one value.")+ lookup = {+ contracts.AccountTableCustomPropertyOperator.GREATER_THAN: "gt",+ contracts.AccountTableCustomPropertyOperator.GREATER_THAN_OR_EQUAL: "gte",+ contracts.AccountTableCustomPropertyOperator.LESS_THAN: "lt",+ contracts.AccountTableCustomPropertyOperator.LESS_THAN_OR_EQUAL: "lte",+ }[operator]+ return Q(**{f"value_num__{lookup}": values[0]}), False+ if operator in {+ contracts.AccountTableCustomPropertyOperator.DATE_EXACT,+ contracts.AccountTableCustomPropertyOperator.DATE_BEFORE,+ contracts.AccountTableCustomPropertyOperator.DATE_AFTER,+ }:+ if data_type != DataType.DATETIME:+ raise InvalidAccountTableColumn("Date operators require a date or datetime custom property.")+ if len(values) != 1:+ raise InvalidAccountTableColumn("Date comparison filters require one value.")+ if operator == contracts.AccountTableCustomPropertyOperator.DATE_EXACT:+ target_date = cast(datetime, values[0]).replace(hour=0, minute=0, second=0, microsecond=0)+ return Q(value_datetime__gte=target_date, value_datetime__lt=target_date + timedelta(days=1)), False+ lookup = {+ contracts.AccountTableCustomPropertyOperator.DATE_BEFORE: "lt",+ contracts.AccountTableCustomPropertyOperator.DATE_AFTER: "gt",+ }[operator]+ return Q(**{f"value_datetime__{lookup}": values[0]}), False+ raise InvalidAccountTableColumn(f"Unsupported custom property filter operator: {operator.value}")+++def _apply_account_table_filters(+ queryset: QuerySet[Account],+ *,+ team_id: int,+ filters: tuple[contracts.AccountTableFilter, ...],+ custom_property_display_types: dict[UUID, DisplayType],+) -> QuerySet[Account]:+ active_relationships = AccountRelationship.objects.for_team(team_id).filter(+ account_id=OuterRef("pk"), ended_at__isnull=True, user_id__isnull=False+ )+ for filter_ in filters:+ if isinstance(filter_, contracts.AccountTableSearchFilter):+ query = filter_.query.strip()+ if query:+ queryset = queryset.filter(Q(name__icontains=query) | Q(external_id__icontains=query))+ elif isinstance(filter_, contracts.AccountTableTagsFilter):+ if filter_.tag_names:+ matching_tags = TaggedItem.objects.filter(+ account_id=OuterRef("pk"), tag__team_id=team_id, tag__name__in=filter_.tag_names+ )+ queryset = queryset.filter(Exists(matching_tags))+ elif isinstance(filter_, contracts.AccountTableAssignedToFilter):+ if filter_.user_ids:+ queryset = queryset.filter(Exists(active_relationships.filter(user_id__in=filter_.user_ids)))+ elif isinstance(filter_, contracts.AccountTableUnassignedFilter):+ queryset = queryset.filter(~Exists(active_relationships))+ elif isinstance(filter_, contracts.AccountTableAccountIdFilter):+ queryset = queryset.filter(id=filter_.account_id)+ elif isinstance(filter_, contracts.AccountTableCustomPropertyFilter):+ active_values = CustomPropertyValue.objects.for_team(team_id).filter(+ account_id=OuterRef("pk"), definition_id=filter_.definition_id, is_deleted=False+ )+ predicate, negate_exists = _custom_property_filter_predicate(+ filter_, custom_property_display_types[filter_.definition_id]+ )+ matching_values = active_values.filter(predicate)+ queryset = queryset.filter(~Exists(matching_values) if negate_exists else Exists(matching_values))+ return queryset+++def _custom_property_sort_output_field(display_type: DisplayType) -> Field:+ return {+ DataType.STRING: TextField(),+ DataType.NUMERIC: FloatField(),+ DataType.BOOLEAN: BooleanField(),+ DataType.DATETIME: DateTimeField(),+ }[DATA_TYPE_BY_DISPLAY_TYPE[display_type]]+++def _apply_account_table_sort(+ queryset: QuerySet[Account],+ *,+ team_id: int,+ sort: contracts.AccountTableSort | None,+ custom_property_display_types: dict[UUID, DisplayType],+) -> QuerySet[Account]:+ if sort is None:+ return queryset.order_by("-created_at", "-id")++ if sort.kind == contracts.AccountTableSortKind.ACCOUNT_FIELD:+ if sort.account_field is None:+ raise InvalidAccountTableColumn("Account field sorting requires a field.")+ direct_fields = {+ contracts.AccountTableField.NAME: "name",+ contracts.AccountTableField.EXTERNAL_ID: "external_id",+ contracts.AccountTableField.CREATED_AT: "created_at",+ contracts.AccountTableField.UPDATED_AT: "updated_at",+ }+ if direct_field := direct_fields.get(sort.account_field):+ queryset = queryset.annotate(_account_table_sort=F(direct_field))+ else:+ queryset = queryset.annotate(_account_table_sort=KeyTextTransform(sort.account_field.value, "_properties"))+ elif sort.kind == contracts.AccountTableSortKind.TAGS:+ tag_values = (+ TaggedItem.objects.filter(account_id=OuterRef("pk"), tag__team_id=team_id)+ .values("account_id")+ .annotate(value=ArrayAgg("tag__name", order_by="tag__name"))+ .values("value")+ )+ queryset = queryset.annotate(_account_table_sort=Subquery(tag_values, output_field=ArrayField(CharField())))+ elif sort.kind == contracts.AccountTableSortKind.NOTE_COUNT:+ note_counts = (+ ResourceNotebook.objects.filter(account_id=OuterRef("pk"))+ .values("account_id")+ .annotate(value=Count("id"))+ .values("value")+ )+ queryset = queryset.annotate(+ _account_table_sort=Coalesce(Subquery(note_counts, output_field=IntegerField()), Value(0))+ )+ elif sort.kind == contracts.AccountTableSortKind.RELATIONSHIP:+ if sort.definition_id is None:+ raise InvalidAccountTableColumn("Relationship sorting requires a definition.")+ relationship_values = (+ AccountRelationship.objects.for_team(team_id)+ .filter(+ account_id=OuterRef("pk"),+ definition_id=sort.definition_id,+ ended_at__isnull=True,+ user_id__isnull=False,+ )+ .values("account_id")+ .annotate(value=ArrayAgg("user_id", order_by="user_id"))+ .values("value")+ )+ queryset = queryset.annotate(+ _account_table_sort=Subquery(relationship_values, output_field=ArrayField(IntegerField()))+ )+ elif sort.kind == contracts.AccountTableSortKind.CUSTOM_PROPERTY:+ if sort.definition_id is None:+ raise InvalidAccountTableColumn("Custom property sorting requires a definition.")+ display_type = custom_property_display_types[sort.definition_id]+ value_field = {+ DataType.STRING: "value_str",+ DataType.NUMERIC: "value_num",+ DataType.BOOLEAN: "value_bool",+ DataType.DATETIME: "value_datetime",+ }[DATA_TYPE_BY_DISPLAY_TYPE[display_type]]+ custom_property_value = CustomPropertyValue.objects.for_team(team_id).filter(+ account_id=OuterRef("pk"), definition_id=sort.definition_id, is_deleted=False+ )+ queryset = queryset.annotate(+ _account_table_sort=Subquery(+ custom_property_value.values(value_field)[:1],+ output_field=_custom_property_sort_output_field(display_type),+ )+ )++ order = F("_account_table_sort")+ primary_order = (+ order.asc(nulls_last=True)+ if sort.direction == contracts.AccountTableSortDirection.ASCENDING+ else order.desc(nulls_last=True)+ )+ return queryset.order_by(primary_order, "id")++def query_accounts_table(*,team_id: int,user_access_control: "UserAccessControl",selection: contracts.AccountTableColumnSelection,+ filters: tuple[contracts.AccountTableFilter, ...],+ sort: contracts.AccountTableSort | None,offset: int,limit: int,) -> contracts.AccountTablePage:- custom_property_display_types = _validate_account_table_definitions(team_id=team_id, selection=selection)+ custom_property_display_types = _validate_account_table_definitions(+ team_id=team_id,+ selection=selection,+ filters=filters,+ sort=sort,+ )- queryset = _accounts_queryset(team_id, user_access_control).order_by("-created_at", "-id")+ queryset = _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,+ )+ queryset = _apply_account_table_sort(+ queryset,+ team_id=team_id,+ sort=sort,+ custom_property_display_types=custom_property_display_types,+ )fetched_accounts = list(queryset[offset : offset + limit + 1])has_more = len(fetched_accounts) > limitaccounts = fetched_accounts[:limit]diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 2e8722666be1..1d7e57bb96f6 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -201,6 +201,87 @@ class AccountTableColumnSelection:custom_property_history_windows: dict[UUID, int] = field(default_factory=dict)+@dataclass(frozen=True, kw_only=True)+class AccountTableSearchFilter:+ query: str+++@dataclass(frozen=True, kw_only=True)+class AccountTableTagsFilter:+ tag_names: tuple[str, ...]+++@dataclass(frozen=True, kw_only=True)+class AccountTableAssignedToFilter:+ user_ids: tuple[int, ...]+++@dataclass(frozen=True, kw_only=True)+class AccountTableUnassignedFilter:+ pass+++@dataclass(frozen=True, kw_only=True)+class AccountTableAccountIdFilter:+ account_id: UUID+++class AccountTableCustomPropertyOperator(str, Enum):+ EXACT = "exact"+ IS_NOT = "is_not"+ CONTAINS = "icontains"+ DOES_NOT_CONTAIN = "not_icontains"+ REGEX = "regex"+ NOT_REGEX = "not_regex"+ GREATER_THAN = "gt"+ GREATER_THAN_OR_EQUAL = "gte"+ LESS_THAN = "lt"+ LESS_THAN_OR_EQUAL = "lte"+ IS_SET = "is_set"+ IS_NOT_SET = "is_not_set"+ DATE_EXACT = "is_date_exact"+ DATE_BEFORE = "is_date_before"+ DATE_AFTER = "is_date_after"+++@dataclass(frozen=True, kw_only=True)+class AccountTableCustomPropertyFilter:+ definition_id: UUID+ operator: AccountTableCustomPropertyOperator+ values: tuple[float | bool | str, ...] = ()+++AccountTableFilter = (+ AccountTableSearchFilter+ | AccountTableTagsFilter+ | AccountTableAssignedToFilter+ | AccountTableUnassignedFilter+ | AccountTableAccountIdFilter+ | AccountTableCustomPropertyFilter+)+++class AccountTableSortKind(str, Enum):+ ACCOUNT_FIELD = "account_field"+ TAGS = "tags"+ NOTE_COUNT = "note_count"+ RELATIONSHIP = "relationship"+ CUSTOM_PROPERTY = "custom_property"+++class AccountTableSortDirection(str, Enum):+ ASCENDING = "asc"+ DESCENDING = "desc"+++@dataclass(frozen=True, kw_only=True)+class AccountTableSort:+ kind: AccountTableSortKind+ direction: AccountTableSortDirection+ account_field: AccountTableField | None = None+ definition_id: UUID | None = None++@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 7e13b151493c..db0217412c63 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@@ -5,7 +5,10 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.schema import (AccountsTableAccountFieldColumn,+ AccountsTableAccountIdFilter,+ AccountsTableAssignedToFilter,AccountsTableCustomPropertyColumn,+ AccountsTableCustomPropertyFilter,AccountsTableCustomPropertyHistoryColumn,AccountsTableCustomPropertyHistoryPoint,AccountsTableNoteCountColumn,@@ -13,7 +16,10 @@ from posthog.schema import (AccountsTableQueryResponse,AccountsTableRelationshipColumn,AccountsTableRow,+ AccountsTableSearchFilter,AccountsTableTagsColumn,+ AccountsTableTagsFilter,+ AccountsTableUnassignedFilter,CachedAccountsTableQueryResponse,)@@ -26,7 +32,10 @@ from posthog.rbac.user_access_control import UserAccessControl, UserAccessControfrom products.customer_analytics.backend.facade import api, contractsACCOUNTS_TABLE_MAX_COLUMNS = 100+ACCOUNTS_TABLE_MAX_FILTERS = 50+ACCOUNTS_TABLE_MAX_FILTER_VALUES = 100ACCOUNTS_TABLE_MAX_PAGE_SIZE = 500+ACCOUNTS_TABLE_MAX_STRING_LENGTH = 1_000class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse]):@@ -81,6 +90,94 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])custom_property_history_windows=custom_property_history_windows,)+ def _filters(self) -> tuple[contracts.AccountTableFilter, ...]:+ query_filters = self.query.filters or []+ if len(query_filters) > ACCOUNTS_TABLE_MAX_FILTERS:+ raise ValidationError(f"Account table queries support up to {ACCOUNTS_TABLE_MAX_FILTERS} filters.")++ filters: list[contracts.AccountTableFilter] = []+ try:+ for filter_ in query_filters:+ if (+ isinstance(filter_, AccountsTableSearchFilter)+ and len(filter_.query) > ACCOUNTS_TABLE_MAX_STRING_LENGTH+ ):+ raise ValidationError(+ f"Account table filter strings support up to {ACCOUNTS_TABLE_MAX_STRING_LENGTH} characters."+ )+ filter_values = (+ filter_.tagNames+ if isinstance(filter_, AccountsTableTagsFilter)+ else filter_.userIds+ if isinstance(filter_, AccountsTableAssignedToFilter)+ else filter_.values or []+ if isinstance(filter_, AccountsTableCustomPropertyFilter)+ else []+ )+ if len(filter_values) > ACCOUNTS_TABLE_MAX_FILTER_VALUES:+ raise ValidationError(+ f"Account table filters support up to {ACCOUNTS_TABLE_MAX_FILTER_VALUES} values."+ )+ if any(+ isinstance(value, str) and len(value) > ACCOUNTS_TABLE_MAX_STRING_LENGTH for value in filter_values+ ):+ raise ValidationError(+ f"Account table filter strings support up to {ACCOUNTS_TABLE_MAX_STRING_LENGTH} characters."+ )+ if isinstance(filter_, AccountsTableSearchFilter):+ filters.append(contracts.AccountTableSearchFilter(query=filter_.query))+ elif isinstance(filter_, AccountsTableTagsFilter):+ filters.append(contracts.AccountTableTagsFilter(tag_names=tuple(filter_.tagNames)))+ elif isinstance(filter_, AccountsTableAssignedToFilter):+ filters.append(contracts.AccountTableAssignedToFilter(user_ids=tuple(filter_.userIds)))+ elif isinstance(filter_, AccountsTableUnassignedFilter):+ filters.append(contracts.AccountTableUnassignedFilter())+ elif isinstance(filter_, AccountsTableAccountIdFilter):+ filters.append(contracts.AccountTableAccountIdFilter(account_id=UUID(filter_.accountId)))+ elif isinstance(filter_, AccountsTableCustomPropertyFilter):+ filters.append(+ contracts.AccountTableCustomPropertyFilter(+ definition_id=UUID(filter_.definitionId),+ operator=contracts.AccountTableCustomPropertyOperator(filter_.operator.value),+ values=tuple(filter_.values or ()),+ )+ )+ except ValueError as error:+ raise ValidationError("Account table filter IDs must be valid UUIDs.") from error+ return tuple(filters)++ def _sort(self) -> contracts.AccountTableSort | None:+ if self.query.sort is None:+ return None++ column = self.query.sort.column+ direction = contracts.AccountTableSortDirection(self.query.sort.direction.value)+ if isinstance(column, AccountsTableAccountFieldColumn):+ return contracts.AccountTableSort(+ kind=contracts.AccountTableSortKind.ACCOUNT_FIELD,+ direction=direction,+ account_field=contracts.AccountTableField(column.field.value),+ )+ if isinstance(column, AccountsTableTagsColumn):+ return contracts.AccountTableSort(kind=contracts.AccountTableSortKind.TAGS, direction=direction)+ if isinstance(column, AccountsTableNoteCountColumn):+ return contracts.AccountTableSort(kind=contracts.AccountTableSortKind.NOTE_COUNT, direction=direction)+ try:+ if isinstance(column, AccountsTableRelationshipColumn):+ return contracts.AccountTableSort(+ kind=contracts.AccountTableSortKind.RELATIONSHIP,+ direction=direction,+ definition_id=UUID(column.definitionId),+ )+ if isinstance(column, AccountsTableCustomPropertyColumn):+ return contracts.AccountTableSort(+ kind=contracts.AccountTableSortKind.CUSTOM_PROPERTY,+ direction=direction,+ definition_id=UUID(column.definitionId),+ )+ except ValueError as error:+ raise ValidationError("Account table sort definition IDs must be valid UUIDs.") from error+def _calculate(self) -> AccountsTableQueryResponse:user_access_control = self.user_access_controlif user_access_control is None:@@ -98,6 +195,8 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])team_id=self.team.id,user_access_control=user_access_control,selection=self._column_selection(),+ filters=self._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 8b8d79322231..daaefe4a41af 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@@ -1,4 +1,4 @@-from datetime import timedelta+from datetime import UTC, datetime, timedeltaimport pytestfrom freezegun import freeze_time@@ -14,17 +14,26 @@ from rest_framework.exceptions import ValidationErrorfrom posthog.schema import (AccountsTableAccountField,AccountsTableAccountFieldColumn,+ AccountsTableAccountIdFilter,+ AccountsTableAssignedToFilter,AccountsTableCustomPropertyColumn,+ AccountsTableCustomPropertyFilter,AccountsTableCustomPropertyHistoryColumn,+ AccountsTableCustomPropertyOperator,AccountsTableNoteCountColumn,AccountsTableQuery,AccountsTableQueryResponse,AccountsTableRelationshipColumn,+ AccountsTableSearchFilter,+ AccountsTableSort,+ AccountsTableSortDirection,AccountsTableTagsColumn,+ AccountsTableTagsFilter,+ AccountsTableUnassignedFilter,)from posthog.constants import AvailableFeature-from posthog.models import OrganizationMembership, Tag, Team+from posthog.models import OrganizationMembership, Tag, Team, Userfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rbac.user_access_control import UserAccessControl@@ -32,7 +41,10 @@ from posthog.rbac.user_access_control import UserAccessControlfrom products.customer_analytics.backend.facade import api, contractsfrom products.customer_analytics.backend.hogql_queries.accounts_table_query_runner import (ACCOUNTS_TABLE_MAX_COLUMNS,+ ACCOUNTS_TABLE_MAX_FILTER_VALUES,+ ACCOUNTS_TABLE_MAX_FILTERS,ACCOUNTS_TABLE_MAX_PAGE_SIZE,+ ACCOUNTS_TABLE_MAX_STRING_LENGTH,AccountsTableQueryRunner,)from products.customer_analytics.backend.models import (@@ -123,7 +135,8 @@ class TestAccountsTableQueryRunner(BaseTest):definitionId=str(numeric_definition.id),windowDays=30,),- ]+ ],+ filters=[],))@@ -164,13 +177,15 @@ class TestAccountsTableQueryRunner(BaseTest):value_num=index,)- with self.assertNumQueries(6):+ with self.assertNumQueries(7):page = api.query_accounts_table(team_id=self.team.id,user_access_control=UserAccessControl(user=self.user, team=self.team),selection=contracts.AccountTableColumnSelection(custom_property_definition_ids=frozenset({definition.id})),+ filters=(),+ sort=None,offset=0,limit=100,)@@ -220,6 +235,329 @@ class TestAccountsTableQueryRunner(BaseTest):assert response.limit == 1assert response.offset == 1+ def test_combines_search_tag_and_active_assignment_filters(self) -> None:+ active_account = create_account(team_id=self.team.id, name="Acme active")+ ended_account = create_account(team_id=self.team.id, name="Acme ended")+ untagged_account = create_account(team_id=self.team.id, name="Acme untagged")+ tag = Tag.objects.create(team=self.team, name="enterprise")+ active_account.tagged_items.create(tag=tag)+ ended_account.tagged_items.create(tag=tag)+ definition = AccountRelationshipDefinition.objects.unscoped().create(team=self.team, name="CSM")+ AccountRelationship.objects.unscoped().create(+ team=self.team,+ account=active_account,+ definition=definition,+ user=self.user,+ )+ AccountRelationship.objects.unscoped().create(+ team=self.team,+ account=ended_account,+ definition=definition,+ user=self.user,+ ended_at=timezone.now(),+ )++ response = self._run(+ AccountsTableQuery(+ columns=[],+ filters=[+ AccountsTableSearchFilter(query="acme"),+ AccountsTableTagsFilter(tagNames=["enterprise"]),+ AccountsTableAssignedToFilter(userIds=[self.user.id]),+ ],+ )+ )++ assert [row.id for row in response.results] == [str(active_account.id)]+ assert str(untagged_account.id) not in {row.id for row in response.results}++ def test_unassigned_and_account_id_filters(self) -> None:+ assigned_account = create_account(team_id=self.team.id, name="Assigned")+ unassigned_account = create_account(team_id=self.team.id, name="Unassigned")+ definition = AccountRelationshipDefinition.objects.unscoped().create(team=self.team, name="CSM")+ AccountRelationship.objects.unscoped().create(+ team=self.team,+ account=assigned_account,+ definition=definition,+ user=self.user,+ )++ unassigned_response = self._run(AccountsTableQuery(columns=[], filters=[AccountsTableUnassignedFilter()]))+ account_response = self._run(+ AccountsTableQuery(+ columns=[],+ filters=[AccountsTableAccountIdFilter(accountId=str(assigned_account.id))],+ )+ )++ assert [row.id for row in unassigned_response.results] == [str(unassigned_account.id)]+ assert [row.id for row in account_response.results] == [str(assigned_account.id)]++ @parameterized.expand(+ [+ ("greater_than", AccountsTableCustomPropertyOperator.GT, [10], {"High"}),+ ("negative_includes_unset", AccountsTableCustomPropertyOperator.IS_NOT, [20], {"Low", "Unset"}),+ ("is_not_set", AccountsTableCustomPropertyOperator.IS_NOT_SET, [], {"Unset"}),+ ]+ )+ def test_filters_typed_custom_properties(+ self,+ _name: str,+ operator: AccountsTableCustomPropertyOperator,+ values: list[int],+ expected_names: set[str],+ ) -> 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)++ response = self._run(+ AccountsTableQuery(+ columns=[],+ filters=[+ AccountsTableCustomPropertyFilter(+ definitionId=str(definition.id),+ operator=operator,+ values=values,+ )+ ],+ )+ )++ assert {row.name for row in response.results} == expected_names++ @parameterized.expand(+ [+ (+ "text_contains",+ DisplayType.TEXT,+ {"value_str": "enterprise"},+ AccountsTableCustomPropertyOperator.ICONTAINS,+ ["ter"],+ {"Set"},+ ),+ (+ "negative_text_includes_unset",+ DisplayType.TEXT,+ {"value_str": "enterprise"},+ AccountsTableCustomPropertyOperator.NOT_ICONTAINS,+ ["zzz"],+ {"Set", "Unset"},+ ),+ (+ "boolean",+ DisplayType.BOOLEAN,+ {"value_bool": True},+ AccountsTableCustomPropertyOperator.EXACT,+ ["true"],+ {"Set"},+ ),+ (+ "date",+ DisplayType.DATE,+ {"value_datetime": datetime(2026, 1, 1, 14, 30, tzinfo=UTC)},+ AccountsTableCustomPropertyOperator.IS_DATE_BEFORE,+ ["2026-02-01T00:00:00Z"],+ {"Set"},+ ),+ ]+ )+ def test_filters_custom_property_operator_families(+ self,+ _name: str,+ display_type: DisplayType,+ value_kwargs: dict[str, object],+ operator: AccountsTableCustomPropertyOperator,+ values: list[str],+ expected_names: set[str],+ ) -> None:+ definition = create_custom_property_definition(+ team_id=self.team.id,+ name=f"Property {_name}",+ display_type=display_type,+ )+ set_account = create_account(team_id=self.team.id, name="Set")+ create_account(team_id=self.team.id, name="Unset")+ CustomPropertyValue.objects.unscoped().create(+ team=self.team,+ account=set_account,+ definition=definition,+ **value_kwargs,+ )++ response = self._run(+ AccountsTableQuery(+ columns=[],+ filters=[+ AccountsTableCustomPropertyFilter(+ definitionId=str(definition.id),+ operator=operator,+ values=values,+ )+ ],+ )+ )++ assert {row.name for row in response.results} == expected_names++ def test_rejects_excessive_filter_count_and_string_length(self) -> None:+ with self.assertRaises(ValidationError):+ self._run(+ AccountsTableQuery(+ columns=[],+ filters=[AccountsTableSearchFilter(query="a")] * (ACCOUNTS_TABLE_MAX_FILTERS + 1),+ )+ )++ with self.assertRaises(ValidationError):+ self._run(+ AccountsTableQuery(+ columns=[],+ filters=[AccountsTableSearchFilter(query="a" * (ACCOUNTS_TABLE_MAX_STRING_LENGTH + 1))],+ )+ )++ def test_rejects_excessive_custom_property_filter_values(self) -> None:+ definition = create_custom_property_definition(+ team_id=self.team.id,+ name="Health score",+ display_type=DisplayType.NUMBER,+ )++ with self.assertRaises(ValidationError):+ self._run(+ AccountsTableQuery(+ columns=[],+ filters=[+ AccountsTableCustomPropertyFilter(+ definitionId=str(definition.id),+ operator=AccountsTableCustomPropertyOperator.EXACT,+ values=list(range(ACCOUNTS_TABLE_MAX_FILTER_VALUES + 1)),+ )+ ],+ )+ )++ def test_sorts_before_paginating_across_supported_column_kinds(self) -> None:+ alpha = create_account(team_id=self.team.id, name="Alpha", _properties={"stripe_customer_id": "cus_z"})+ beta = create_account(team_id=self.team.id, name="Beta", _properties={"stripe_customer_id": "cus_a"})+ create_account(team_id=self.team.id, name="Gamma")+ alpha.tagged_items.create(tag=Tag.objects.create(team=self.team, name="z-tag"))+ beta.tagged_items.create(tag=Tag.objects.create(team=self.team, name="a-tag"))+ for account, count in [(alpha, 2), (beta, 1)]:+ for _ in range(count):+ ResourceNotebook.objects.create(+ account=account,+ notebook=Notebook.objects.create(team=self.team, created_by=self.user),+ )+ relationship_definition = AccountRelationshipDefinition.objects.unscoped().create(team=self.team, name="CSM")+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")+ AccountRelationship.objects.unscoped().create(+ team=self.team, account=alpha, definition=relationship_definition, user=self.user+ )+ AccountRelationship.objects.unscoped().create(+ team=self.team, account=beta, definition=relationship_definition, user=other_user+ )+ custom_property_definition = create_custom_property_definition(+ team_id=self.team.id, name="MRR", display_type=DisplayType.CURRENCY+ )+ CustomPropertyValue.objects.unscoped().create(+ team=self.team, account=alpha, definition=custom_property_definition, value_num=20+ )+ CustomPropertyValue.objects.unscoped().create(+ team=self.team, account=beta, definition=custom_property_definition, value_num=5+ )++ paginated = self._run(+ AccountsTableQuery(+ columns=[],+ filters=[],+ sort=AccountsTableSort(+ column=AccountsTableAccountFieldColumn(field=AccountsTableAccountField.NAME),+ direction=AccountsTableSortDirection.ASC,+ ),+ limit=1,+ offset=1,+ )+ )+ assert [row.name for row in paginated.results] == ["Beta"]+ assert paginated.hasMore is True++ sort_cases = [+ (+ AccountsTableAccountFieldColumn(field=AccountsTableAccountField.STRIPE_CUSTOMER_ID),+ ["Beta", "Alpha", "Gamma"],+ ),+ (AccountsTableTagsColumn(), ["Beta", "Alpha", "Gamma"]),+ (AccountsTableNoteCountColumn(), ["Alpha", "Beta", "Gamma"]),+ (+ AccountsTableRelationshipColumn(definitionId=str(relationship_definition.id)),+ ["Alpha", "Beta", "Gamma"],+ ),+ (+ AccountsTableCustomPropertyColumn(definitionId=str(custom_property_definition.id)),+ ["Beta", "Alpha", "Gamma"],+ ),+ ]+ for column, expected_names in sort_cases:+ with self.subTest(column_type=type(column).__name__):+ direction = (+ AccountsTableSortDirection.DESC+ if isinstance(column, AccountsTableNoteCountColumn)+ else AccountsTableSortDirection.ASC+ )+ response = self._run(+ AccountsTableQuery(+ columns=[],+ filters=[],+ sort=AccountsTableSort(column=column, direction=direction),+ )+ )+ assert [row.name for row in response.results] == expected_names++ def test_rejects_regex_custom_property_filters(self) -> None:+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")++ with self.assertRaises(ValidationError):+ self._run(+ AccountsTableQuery(+ columns=[],+ filters=[+ AccountsTableCustomPropertyFilter(+ definitionId=str(definition.id),+ operator=AccountsTableCustomPropertyOperator.REGEX,+ values=["^enter.*"],+ )+ ],+ )+ )++ def test_rejects_operator_incompatible_with_custom_property_type(self) -> None:+ definition = create_custom_property_definition(+ team_id=self.team.id, name="MRR", display_type=DisplayType.CURRENCY+ )++ with self.assertRaises(ValidationError):+ self._run(+ AccountsTableQuery(+ columns=[],+ filters=[+ AccountsTableCustomPropertyFilter(+ definitionId=str(definition.id),+ operator=AccountsTableCustomPropertyOperator.ICONTAINS,+ values=["2"],+ )+ ],+ )+ )+@parameterized.expand(["relationship", "custom_property"])def test_rejects_definition_from_another_team(self, column_kind: str) -> None:other_team = Team.objects.create(organization=self.organization)@@ -234,7 +572,38 @@ class TestAccountsTableQueryRunner(BaseTest):column = AccountsTableCustomPropertyColumn(definitionId=str(custom_property_definition.id))with self.assertRaises(ValidationError):- self._run(AccountsTableQuery(columns=[column]))+ self._run(AccountsTableQuery(columns=[column], filters=[]))++ @parameterized.expand(["filter", "sort"])+ def test_rejects_filter_or_sort_definition_from_another_team(self, query_part: str) -> None:+ other_team = Team.objects.create(organization=self.organization)+ definition = create_custom_property_definition(team_id=other_team.id, name="Other plan")+ filter_ = (+ AccountsTableCustomPropertyFilter(+ definitionId=str(definition.id),+ operator=AccountsTableCustomPropertyOperator.IS_SET,+ values=[],+ )+ if query_part == "filter"+ else None+ )+ sort = (+ AccountsTableSort(+ column=AccountsTableCustomPropertyColumn(definitionId=str(definition.id)),+ direction=AccountsTableSortDirection.ASC,+ )+ if query_part == "sort"+ else None+ )++ with self.assertRaises(ValidationError):+ self._run(+ AccountsTableQuery(+ columns=[],+ filters=[filter_] if filter_ else [],+ sort=sort,+ )+ )def test_rejects_history_for_non_numeric_custom_property(self) -> None:definition = create_custom_property_definition(team_id=self.team.id, name="Plan")@@ -242,14 +611,18 @@ class TestAccountsTableQueryRunner(BaseTest):with self.assertRaises(ValidationError):self._run(AccountsTableQuery(- columns=[AccountsTableCustomPropertyHistoryColumn(definitionId=str(definition.id), windowDays=30)]+ columns=[AccountsTableCustomPropertyHistoryColumn(definitionId=str(definition.id), windowDays=30)],+ filters=[],))def test_rejects_malformed_definition_id(self) -> None:with self.assertRaises(ValidationError):self._run(- AccountsTableQuery(columns=[AccountsTableCustomPropertyColumn(definitionId="not-a-definition-id")])+ AccountsTableQuery(+ columns=[AccountsTableCustomPropertyColumn(definitionId="not-a-definition-id")],+ filters=[],+ ))@pytest.mark.ee@@ -273,7 +646,7 @@ class TestAccountsTableQueryRunner(BaseTest):)blocked_runner = AccountsTableQueryRunner(- query=AccountsTableQuery(columns=[]),+ query=AccountsTableQuery(columns=[], filters=[], limit=1),team=self.team,user=self.user,)@@ -284,7 +657,7 @@ class TestAccountsTableQueryRunner(BaseTest):blocking_access.delete()unblocked_cache_key = AccountsTableQueryRunner(- query=AccountsTableQuery(columns=[]),+ query=AccountsTableQuery(columns=[], filters=[], limit=1),team=self.team,user=self.user,).get_cache_key()@@ -304,11 +677,27 @@ class TestAccountsTableQueryAPI(APIBaseTest):)return value+ def test_query_endpoint_rejects_unsupported_filters(self) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/query/",+ {+ "query": {+ "kind": "AccountsTableQuery",+ "columns": [],+ "filters": [{"kind": "unsupported"}],+ },+ "refresh": "force_blocking",+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+def test_query_endpoint_requires_account_scope_and_dispatches(self) -> None:account = create_account(team_id=self.team.id, name="Acme")endpoint = f"/api/projects/{self.team.id}/query/"payload = {- "query": AccountsTableQuery(columns=[]).model_dump(),+ "query": AccountsTableQuery(columns=[], filters=[]).model_dump(),"refresh": "force_blocking",}diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 47a88973f8d9..c3a28ff5fe94 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -221,7 +221,7 @@ The tool is registered for the page regardless of agent mode. The Customer analy- `products/customer_analytics/backend/models` — the `Account` model (`external_id` = group key).- `products/customer_analytics/backend/hogql_queries/accounts_query_runner.py` — the current Accounts page query runner, which builds positional list rows through HogQL.-- `products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py` — the typed Postgres-only `AccountsTableQuery` runner. It returns keyed rows for the planned Accounts page migration but is not wired into the page yet.+- `products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py` — the typed Postgres-only `AccountsTableQuery` runner. It returns keyed rows, applies typed list filters and server-side sorting, and is not wired into the page yet.- `products/customer_analytics/backend/max_tools/` — `OpenAccountTool` and other account Max tools.- `ee/hogai/core/agent_modes/presets/customer_analytics.py` — the Customer analytics agent mode (gated by the `customer-analytics-csp` flag).diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2cde45ab97b9..3d9565a267be 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -846,12 +846,52 @@ export namespace Schemas {kind?: 'account_field';}+ export interface AccountsTableAccountIdFilter {+ accountId: string;+ kind?: 'account_id';+ }++ 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 type AccountsTableCustomPropertyOperator = typeof AccountsTableCustomPropertyOperator[keyof typeof AccountsTableCustomPropertyOperator];+++ export const AccountsTableCustomPropertyOperator = {+ Exact: 'exact',+ IsNot: 'is_not',+ Icontains: 'icontains',+ NotIcontains: 'not_icontains',+ Regex: 'regex',+ NotRegex: 'not_regex',+ Gt: 'gt',+ Gte: 'gte',+ Lt: 'lt',+ Lte: 'lte',+ IsSet: 'is_set',+ IsNotSet: 'is_not_set',+ IsDateExact: 'is_date_exact',+ IsDateBefore: 'is_date_before',+ IsDateAfter: 'is_date_after',+ } as const;++ export interface AccountsTableCustomPropertyFilter {+ definitionId: string;+ kind?: 'custom_property';+ operator: AccountsTableCustomPropertyOperator;+ /** Values interpreted according to the custom property definition's display type. */+ values?: (string | number | boolean)[] | null;+ }+export type WindowDays = typeof WindowDays[keyof typeof WindowDays];@@ -891,6 +931,22 @@ export namespace Schemas {kind?: 'relationship';}+ export interface AccountsTableSearchFilter {+ kind?: 'search';+ query: string;+ }++ export interface AccountsTableTagsFilter {+ kind?: 'tags';+ /** Match accounts carrying any of these tag names. */+ tagNames: string[];+ }++ export const AccountsTableUnassignedFilterValue = {+ kind: 'unassigned',+ } as const;+ export type AccountsTableUnassignedFilter = typeof AccountsTableUnassignedFilterValue;+/*** Requested direct Account fields, keyed by their typed field reference.*/@@ -955,15 +1011,32 @@ export namespace Schemas {warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;}+ export type AccountsTableSortDirection = typeof AccountsTableSortDirection[keyof typeof AccountsTableSortDirection];+++ export const AccountsTableSortDirection = {+ Asc: 'asc',+ Desc: 'desc',+ } as const;++ export interface AccountsTableSort {+ /** A typed column that supports server-side sorting. */+ column: AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn;+ direction: AccountsTableSortDirection;+ }+export interface AccountsTableQuery {/** Columns to load for each account. Account identity fields are always returned. */columns: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[];+ /** Filters are combined with AND. Values within tag and assignment filters use OR. */+ filters?: (AccountsTableSearchFilter | AccountsTableTagsFilter | AccountsTableAssignedToFilter | AccountsTableUnassignedFilter | AccountsTableAccountIdFilter | AccountsTableCustomPropertyFilter)[] | null;kind?: 'AccountsTableQuery';limit?: number | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;offset?: number | null;response?: AccountsTableQueryResponse | null;+ sort?: AccountsTableSort | null;tags?: QueryLogTags | null;/** version of the node, used for schema migrations */version?: number | null;