: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): instant accounts sort when fully loaded (#71720)
jake sciottod334c96fa5d6
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex c5df8301e447..c1945d981e62 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -85,7 +85,22 @@ Value suggestions load from`GET /api/projects/:team_id/custom_property_definitio**Tile display** (title / subtitle / value format). A tile also carries two optional presentation fields, independent of the metric: `caption` (custom subtitle) and `format` (`TileValueFormat` = `unit`/`currency`/`percentage`, a subset of `OverviewGrid`'s `WebAnalyticsItemKind` so `format ?? 'unit'` maps 1:1 to the render `kind`). `tileCaption(tile)` resolves the subtitle: the trimmed custom `caption` when set, else `autoCaption(tile)` (the derived `agg of col × n` / `col op val` text; `count` has no derived caption, so a custom one is the only subtitle it can show). The editor edits `caption` (empty → `undefined`) and `format` (`unit` → `undefined`); both flow through the row's `emit(patch)` merge so a metric edit never drops them. Render formatting lives in `OverviewGrid.formatItem`: `currency` uses the team `baseCurrency`, `percentage` treats the value as already in percent units (`85` → "85%", combine with `scale × 100` for a 0-1 fraction). Both fields ride along in `properties.tiles` (no backend/schema/migration) and default cleanly for older saved/legacy tiles.-Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemoved`), else the backend gets an `orderBy` referencing a missing alias.+### Sorting (hybrid client / server)++Clicking a column header toggles `accountsLogic.sortOrder` (asc → desc → off, `toggleSort`).+How that sort is applied depends on whether the whole matching set is already loaded, tracked by the `canSortClientSide` selector (`!listHasMoreData && !listPaginated`):++- **Fully loaded (the common case — one page, no "Load more"):** `canSortClientSide` is true.+ The list query carries **no** `orderBy`, so toggling a header does not change the query and never refetches.+ Instead the loaded rows are reordered in the browser: the `accountsLogic.sortedRowsTransformer` selector (wrapping `sortAccountRows` from `accountsSort.ts`) is passed by `AccountsHogQLTable` into the DataTable's `dataTableRowsTransformer` context seam — sorting is instant.+ `sortAccountRows` reads each cell by its position in the row's result array (the name tuple sorts by `.name`, relationship/tag arrays join to a string, numbers sort numerically), is stable, and always sinks empty cells to the bottom in both directions.+- **Paginated (more rows than one page):** `canSortClientSide` is false, so the query carries an `orderBy` (built via `orderByExpression`, so numeric custom properties sort numerically server-side too) and ClickHouse sorts the **entire** set and returns the globally-correct top page; the transformer is inactive (rows are shown in server order). Toggling a header refetches, as before.++`listPaginated` is what makes this safe: it is set when the user pages past the first page (`loadNextData`, connected from the list `dataNodeLogic`) and reset on every fresh load (`loadData`).+Without it, paging to the end of a large list would flip `listHasMoreData` to false mid-session, drop the `orderBy`, and reset the query back to page one — discarding the accumulated rows.+Resetting on fresh load lets a filtered-down set (now ≤ one page) return to instant client-side sort.++Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemoved`); otherwise a server-side sort would reference a missing SELECT alias.## The expanded rowdiff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsxindex 1db72eb03de3..eaea965e5936 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx@@ -596,7 +596,7 @@ function AccountsHogQLSkeleton(): JSX.Element {}export function AccountsHogQLTable(): JSX.Element {- const { hogqlQuery, accountsQuerySource } = useValues(accountsLogic)+ const { hogqlQuery, accountsQuerySource, sortedRowsTransformer } = useValues(accountsLogic)const { responseLoading, response } = useValues(dataNodeLogic)const contextColumns = useContextColumns()const expandable = useExpandable()@@ -616,6 +616,7 @@ export function AccountsHogQLTable(): JSX.Element {context={{columns: contextColumns,expandable,+ dataTableRowsTransformer: sortedRowsTransformer,dataNodeLogicKey: ACCOUNTS_HOGQL_DATA_NODE_KEY,emptyStateHeading: 'There are no matching accounts for this query',emptyStateDetail: 'Try adjusting the filters or refreshing',diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.tsindex 5c94daf75d6b..1d31875967aa 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts@@ -337,7 +337,6 @@ describe('accountsLogic', () => {it('toggleSort on a fresh column starts ascending', () => {logic.actions.toggleSort('notebook_count')expect(logic.values.sortOrder).toEqual({ column: 'notebook_count', direction: 'asc' })- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['notebook_count'])})it('toggleSort cycles asc -> desc -> null on repeated clicks', () => {@@ -345,10 +344,8 @@ describe('accountsLogic', () => {expect(logic.values.sortOrder?.direction).toBe('asc')logic.actions.toggleSort('notebook_count')expect(logic.values.sortOrder).toEqual({ column: 'notebook_count', direction: 'desc' })- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['notebook_count DESC'])logic.actions.toggleSort('notebook_count')expect(logic.values.sortOrder).toBeNull()- expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()})it('toggleSort on a different column resets to ascending', () => {@@ -356,17 +353,38 @@ describe('accountsLogic', () => {logic.actions.toggleSort('notebook_count') // desclogic.actions.toggleSort('csm')expect(logic.values.sortOrder).toEqual({ column: 'csm', direction: 'asc' })- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['csm'])})- it('arbitrary column sorts by its alias directly', () => {+ it('leaves orderBy off while the full list is loaded, for instant client-side sort', () => {+ expect(logic.values.canSortClientSide).toBe(true)+ logic.actions.toggleSort('notebook_count')+ expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()+ expect(logic.values.sortedRowsTransformer).toEqual(expect.any(Function))+ logic.actions.toggleSort('notebook_count') // desc+ expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()+ })++ it('adds orderBy once the list is paginated, for a global server-side sort', () => {+ logic.actions.listLoadNextData()+ expect(logic.values.canSortClientSide).toBe(false)+ logic.actions.toggleSort('notebook_count')+ expect(logic.values.sortedRowsTransformer).toBeUndefined()+ expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['notebook_count'])+ logic.actions.toggleSort('notebook_count') // desc+ expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['notebook_count DESC'])+ })++ it('returns to client-side sort after a fresh load re-evaluates pagination', () => {+ logic.actions.listLoadNextData()logic.actions.toggleSort('name')expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['name'])- logic.actions.toggleSort('name')- expect(orderByOf(logic.values.hogqlQuery.source)).toEqual(['name DESC'])+ logic.actions.listLoadData()+ expect(logic.values.canSortClientSide).toBe(true)+ expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()})- it('skips the orderBy when the sorted role column has no matching definition', () => {+ it('skips the server orderBy when the sorted role column has no matching definition', () => {+ logic.actions.listLoadNextData()logic.actions.toggleSort('csm')accountsColumnConfigLogic.findMounted()?.actions.loadRelationshipDefinitionsSuccess([])expect(orderByOf(logic.values.hogqlQuery.source)).toBeUndefined()@@ -401,6 +419,7 @@ describe('accountsLogic', () => {'sorts a %s column by its value cast to a float',(displayType) => {selectCustomProperty(displayType)+ logic.actions.listLoadNextData()logic.actions.toggleSort(alias)expect(orderByOf(logic.values.hogqlQuery.source)).toEqual([floatExpr])logic.actions.toggleSort(alias) // desc@@ -410,6 +429,7 @@ describe('accountsLogic', () => {it('sorts a non-numeric custom property lexically by its alias', () => {selectCustomProperty('text')+ logic.actions.listLoadNextData()logic.actions.toggleSort(alias)expect(orderByOf(logic.values.hogqlQuery.source)).toEqual([alias])})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex bf960f738794..0589d664434f 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -11,8 +11,9 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'-import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'-import { AccountsQuery, DataTableNode, NodeKind } from '~/queries/schema/schema-general'+import { type DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'+import { AccountsQuery, DataNode, DataTableNode, NodeKind, RefreshType } from '~/queries/schema/schema-general'import type { AccountCustomPropertyFilter, UserBasicType } from '~/types'import {@@ -40,6 +41,7 @@ import {DEFAULT_ACCOUNT_TAB,} from './accountsExpansionLogic'import { accountsOverviewTilesLogic, TileFilter } from './accountsOverviewTilesLogic'+import { sortAccountRows } from './accountsSort'import { normalizeRoleFilter } from './accountsViewState'import { AccountsEvents } from './constants'@@ -190,6 +192,7 @@ export interface accountsLogicValues {overviewMetrics: string[] // accountsOverviewTilesLogictileFilter: TileFilter | null // accountsOverviewTilesLogicmineOnly: boolean // customerAnalyticsSceneLogic+ listHasMoreData: boolean // dataNodeLogiccurrentTeamId: number | null // teamLogicuser: UserType | null // userLogicaccountIdFilter: string | null@@ -198,16 +201,19 @@ export interface accountsLogicValues {allRolesUnassigned: booleanassignedToCurrentUser: booleanassignedToFilter: RoleFilterValue+ canSortClientSide: booleancurrentUserId: number | nullcustomPropertyFilters: AccountCustomPropertyFilter[]hogqlQuery: DataTableNodeisRoleSaving: (accountId: string, column: string) => boolean+ listPaginated: booleanmetricsQuery: AccountsQuery | nullrelationshipOverrides: Record<string, number[]>savingRoles: Record<string, true>searchInput: stringsearchQuery: stringsortOrder: AccountSortOrder+ sortedRowsTransformer: ((rows: DataTableRow[]) => DataTableRow[]) | undefinedtagsFilter: string[]viewUrlState: AccountsViewUrlState}@@ -256,6 +262,17 @@ export interface accountsLogicActions {setMineOnly: (mineOnly: boolean) => {mineOnly: boolean} // customerAnalyticsSceneLogic+ listLoadData: (+ refresh?: RefreshType | undefined,+ alreadyRunningQueryId?: string | undefined,+ overrideQuery?: DataNode<Record<string, any>> | undefined+ ) => {+ overrideQuery: DataNode<Record<string, any>> | undefined+ pollOnly: boolean+ queryId: string+ refresh: RefreshType | undefined+ } // dataNodeLogic+ listLoadNextData: () => any // dataNodeLogicensureAllMembersLoaded: () => {value: true} // membersLogic@@ -378,6 +395,12 @@ export interface accountsLogicMeta {customPropertyFilters: AccountCustomPropertyFilter[],columnDisplay: AccountColumnDisplayState) => AccountsViewUrlState+ canSortClientSide: (listHasMoreData: boolean, listPaginated: boolean) => boolean+ sortedRowsTransformer: (+ canSortClientSide: boolean,+ sortOrder: AccountSortOrder,+ visibleColumnNames: string[]+ ) => ((rows: DataTableRow[]) => DataTableRow[]) | undefinedhogqlQuery: (searchQuery: string,tagsFilter: string[],@@ -386,6 +409,7 @@ export interface accountsLogicMeta {accountIdFilter: string | null,tileFilter: TileFilter | null,sortOrder: AccountSortOrder,+ canSortClientSide: boolean,querySelectColumns: string[],visibleColumnNames: string[],customPropertyFilters: AccountCustomPropertyFilter[],@@ -439,6 +463,8 @@ export const accountsLogic = kea<accountsLogicType>([['metrics as overviewMetrics', 'tileFilter'],customerAnalyticsSceneLogic,['mineOnly'],+ dataNodeLogic({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY } as DataNodeLogicProps),+ ['hasMoreData as listHasMoreData'],],actions: [accountsColumnConfigLogic,@@ -461,6 +487,8 @@ export const accountsLogic = kea<accountsLogicType>([['loadUserSuccess'],membersLogic,['ensureAllMembersLoaded'],+ dataNodeLogic({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY } as DataNodeLogicProps),+ ['loadData as listLoadData', 'loadNextData as listLoadNextData'],],})),actions({@@ -552,6 +580,18 @@ export const accountsLogic = kea<accountsLogicType>([setSortOrder: (_, { sortOrder }) => sortOrder,},],+ // Keeps server-side sort while paging, so reaching the last page never drops the+ // orderBy and collapses the accumulated rows back to page one. Resetting on every+ // listLoadData is deliberate even for the refetch a sort-while-paginated triggers:+ // that request already carries the new orderBy, and its response replaces the+ // accumulated pages with one server-sorted page that is safe to client-sort next.+ listPaginated: [+ false,+ {+ listLoadData: () => false,+ listLoadNextData: () => true,+ },+ ],savingRoles: [{} as Record<string, true>,{@@ -668,6 +708,21 @@ export const accountsLogic = kea<accountsLogicType>([return state},],+ canSortClientSide: [+ (s) => [s.listHasMoreData, s.listPaginated],+ (listHasMoreData: boolean, listPaginated: boolean): boolean => !listHasMoreData && !listPaginated,+ ],+ sortedRowsTransformer: [+ (s) => [s.canSortClientSide, s.sortOrder, s.visibleColumnNames],+ (+ canSortClientSide: boolean,+ sortOrder: AccountSortOrder,+ visibleColumnNames: string[]+ ): ((rows: DataTableRow[]) => DataTableRow[]) | undefined =>+ canSortClientSide && sortOrder+ ? (rows: DataTableRow[]): DataTableRow[] => sortAccountRows(rows, sortOrder, visibleColumnNames)+ : undefined,+ ],hogqlQuery: [(s) => [s.searchQuery,@@ -677,6 +732,7 @@ export const accountsLogic = kea<accountsLogicType>([s.accountIdFilter,s.tileFilter,s.sortOrder,+ s.canSortClientSide,s.querySelectColumns,s.visibleColumnNames,s.customPropertyFilters,@@ -691,6 +747,7 @@ export const accountsLogic = kea<accountsLogicType>([accountIdFilter: string | null,tileFilter: TileFilter | null,sortOrder: AccountSortOrder,+ canSortClientSide: boolean,querySelectColumns: string[],visibleColumnNames: string[],customPropertyFilters: AccountCustomPropertyFilter[],@@ -715,7 +772,7 @@ export const accountsLogic = kea<accountsLogicType>([// HogQL ORDER BY resolves SELECT aliases by name, so the visible column// name works directly. Skip sorts on columns the translation dropped// (a legacy role with no matching definition) — the alias wouldn't resolve.- if (sortOrder && visibleColumnNames.includes(sortOrder.column)) {+ if (sortOrder && !canSortClientSide && visibleColumnNames.includes(sortOrder.column)) {const expr = orderByExpression(sortOrder.column, aliasToDefinition)source.orderBy = [sortOrder.direction === 'asc' ? expr : `${expr} DESC`]}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsSort.test.tsnew file mode 100644index 000000000000..5fc64b32e5ac--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsSort.test.ts@@ -0,0 +1,87 @@+import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'++import type { AccountSortOrder } from './accountsLogic'+import { sortAccountRows } from './accountsSort'++const COLUMNS = ['name', 'notebook_count', 'csm']++const buildRow = ({+ name,+ count = 0,+ csm = [],+}: {+ name: string+ count?: number | null+ csm?: number[]+}): DataTableRow => ({+ result: [{ name, external_id: name, id: name }, count, csm],+})++const cellAt = (row: DataTableRow, index: number): unknown => (row.result as unknown[])[index]+const names = (rows: DataTableRow[]): string[] => rows.map((r) => (cellAt(r, 0) as { name: string }).name)+const counts = (rows: DataTableRow[]): unknown[] => rows.map((r) => cellAt(r, 1))++describe('sortAccountRows', () => {+ it.each([+ ['there is no active sort', null as AccountSortOrder],+ ['the sorted column is not visible', { column: 'missing', direction: 'asc' } as AccountSortOrder],+ ])('returns the same rows untouched when %s', (_label, sortOrder) => {+ const rows = [buildRow({ name: 'B' }), buildRow({ name: 'A' })]+ expect(sortAccountRows(rows, sortOrder, COLUMNS)).toBe(rows)+ })++ it('sorts the name tuple column by its name, case-insensitively, in both directions', () => {+ const rows = [buildRow({ name: 'Charlie' }), buildRow({ name: 'alpha' }), buildRow({ name: 'Bravo' })]+ expect(names(sortAccountRows(rows, { column: 'name', direction: 'asc' }, COLUMNS))).toEqual([+ 'alpha',+ 'Bravo',+ 'Charlie',+ ])+ expect(names(sortAccountRows(rows, { column: 'name', direction: 'desc' }, COLUMNS))).toEqual([+ 'Charlie',+ 'Bravo',+ 'alpha',+ ])+ })++ it('sorts a numeric column numerically, not lexically', () => {+ const rows = [+ buildRow({ name: 'a', count: 2 }),+ buildRow({ name: 'b', count: 10 }),+ buildRow({ name: 'c', count: 1 }),+ ]+ expect(counts(sortAccountRows(rows, { column: 'notebook_count', direction: 'asc' }, COLUMNS))).toEqual([+ 1, 2, 10,+ ])+ })++ it.each([['asc'], ['desc']] as const)('always sorts empty cells last when %s', (direction) => {+ const rows = [+ buildRow({ name: 'a', count: null }),+ buildRow({ name: 'b', count: 5 }),+ buildRow({ name: 'c', count: null }),+ ]+ expect(counts(sortAccountRows(rows, { column: 'notebook_count', direction }, COLUMNS))).toEqual([5, null, null])+ })++ it('treats an empty relationship array as an empty cell (sorts last)', () => {+ const rows = [buildRow({ name: 'unassigned', csm: [] }), buildRow({ name: 'assigned', csm: [42] })]+ expect(names(sortAccountRows(rows, { column: 'csm', direction: 'asc' }, COLUMNS))).toEqual([+ 'assigned',+ 'unassigned',+ ])+ })++ it('keeps equal-keyed rows in their incoming order (stable)', () => {+ const rows = [+ buildRow({ name: 'first', count: 5 }),+ buildRow({ name: 'second', count: 5 }),+ buildRow({ name: 'third', count: 5 }),+ ]+ expect(names(sortAccountRows(rows, { column: 'notebook_count', direction: 'asc' }, COLUMNS))).toEqual([+ 'first',+ 'second',+ 'third',+ ])+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountsSort.ts b/products/customer_analytics/frontend/components/Accounts/accountsSort.tsnew file mode 100644index 000000000000..ff55f6456700--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountsSort.ts@@ -0,0 +1,66 @@+import type { DataTableRow } from '~/queries/nodes/DataTable/dataTableLogic'++import type { AccountSortOrder } from './accountsLogic'++// `0` and `false` are real values, not empty+function isEmptyCell(value: unknown): boolean {+ if (value === null || value === undefined || value === '') {+ return true+ }+ return Array.isArray(value) && value.length === 0+}++// The name column arrives as a { name, external_id, id } tuple, relationship/tag columns as arrays+function getSortKey(value: unknown): number | string {+ if (typeof value === 'number') {+ return value+ }+ if (Array.isArray(value)) {+ return value.join(',')+ }+ if (value && typeof value === 'object') {+ const name = (value as { name?: unknown }).name+ return typeof name === 'string' ? name : String(value)+ }+ return String(value)+}++function compareNonEmpty(a: unknown, b: unknown): number {+ const ka = getSortKey(a)+ const kb = getSortKey(b)+ if (typeof ka === 'number' && typeof kb === 'number') {+ return ka < kb ? -1 : ka > kb ? 1 : 0+ }+ // numeric-aware collation so "2" sorts before "10"+ return String(ka).localeCompare(String(kb), undefined, { numeric: true, sensitivity: 'base' })+}++function getCellAt(row: DataTableRow, index: number): unknown {+ return Array.isArray(row.result) ? row.result[index] : undefined+}++export function sortAccountRows(+ rows: DataTableRow[],+ sortOrder: AccountSortOrder,+ visibleColumnNames: string[]+): DataTableRow[] {+ if (!sortOrder) {+ return rows+ }+ const index = visibleColumnNames.indexOf(sortOrder.column)+ if (index < 0) {+ return rows+ }+ const direction = sortOrder.direction === 'desc' ? -1 : 1+ return [...rows].sort((a, b) => {+ const av = getCellAt(a, index)+ const bv = getCellAt(b, index)+ const aEmpty = isEmptyCell(av)+ const bEmpty = isEmptyCell(bv)+ if (aEmpty || bEmpty) {+ // empty cells sort last in both directions+ return aEmpty === bEmpty ? 0 : aEmpty ? 1 : -1+ }+ return compareNonEmpty(av, bv) * direction+ })+}