Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(logs): hold group-by state as an ordered dimension array (#72246)

Jon McCallum77556c841942
diff --git a/products/logs/frontend/components/LogsGroupBy/LogsGroupByResults.tsx b/products/logs/frontend/components/LogsGroupBy/LogsGroupByResults.tsx
index 0fcaabe06eef..e11c18ead526 100644
--- a/products/logs/frontend/components/LogsGroupBy/LogsGroupByResults.tsx
+++ b/products/logs/frontend/components/LogsGroupBy/LogsGroupByResults.tsx
@@ -32,11 +32,11 @@ export function LogsGroupByResults({ id }: { id: string }): JSX.Element {
logsGroupByLogic({ id })
)
const { setOrderGroupsBy } = useActions(logsGroupByLogic({ id }))
- const { groupBy } = useValues(logsViewerConfigLogic({ id }))
+ const { groupBys } = useValues(logsViewerConfigLogic({ id }))
// The Group view with no key chosen: prompt for one instead of showing an empty table.
- // No query runs in this state (the logic's loader guards on a null key).
- if (!groupBy) {
+ // No query runs in this state (the logic's loader guards on empty dimensions).
+ if (groupBys.length === 0) {
return (
<div className="flex-1 min-h-0 flex items-center justify-center text-muted" data-attr="logs-group-by-empty">
Pick an attribute to group by
@@ -45,11 +45,11 @@ export function LogsGroupByResults({ id }: { id: string }): JSX.Element {
}
const columns: LemonTableColumns<_LogsGroupByGroupApi> = [
- {
- title: groupBy.key,
- dataIndex: 'value',
- render: (_, row) => <span className="font-mono text-xs">{row.value}</span>,
- },
+ // One value column per dimension, in pick order.
+ ...groupBys.map((dimension, index): LemonTableColumns<_LogsGroupByGroupApi>[number] => ({
+ title: dimension.key,
+ render: (_, row) => <span className="font-mono text-xs">{row.values[index]}</span>,
+ })),
{
title: 'Logs',
dataIndex: 'log_count',
@@ -106,7 +106,9 @@ export function LogsGroupByResults({ id }: { id: string }): JSX.Element {
? 'Grouping failed — try a shorter time range or narrower filters'
: 'No groups found for the current filters'
}
- rowKey="value"
+ // Row identity is the full value tuple: with combined dimensions, groups can
+ // share a first value, and keying on `value` alone would duplicate React keys.
+ rowKey={(row) => JSON.stringify(row.values)}
size="small"
/>
</div>
diff --git a/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.test.ts b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.test.ts
new file mode 100644
index 000000000000..b77196e43365
--- /dev/null
+++ b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.test.ts
@@ -0,0 +1,52 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { logsGroupByCreate } from 'products/logs/frontend/generated/api'
+
+import { logsViewerConfigLogic } from '../LogsViewer/config/logsViewerConfigLogic'
+import { logsGroupByLogic } from './logsGroupByLogic'
+
+jest.mock('lib/api')
+jest.mock('products/logs/frontend/generated/api')
+
+describe('logsGroupByLogic', () => {
+ let logic: ReturnType<typeof logsGroupByLogic.build>
+ let configLogic: ReturnType<typeof logsViewerConfigLogic.build>
+
+ beforeEach(() => {
+ localStorage.clear()
+ initKeaTests()
+ jest.clearAllMocks()
+ ;(logsGroupByCreate as jest.Mock).mockResolvedValue({
+ groups: [],
+ total_groups: 0,
+ total_logs: 0,
+ truncated: false,
+ })
+ configLogic = logsViewerConfigLogic({ id: 'test' })
+ configLogic.mount()
+ logic = logsGroupByLogic({ id: 'test' })
+ logic.mount()
+ })
+
+ it('queries with the ordered dimension list and not at all without dimensions', async () => {
+ // Mounting with no dimensions picked must not fire the aggregation.
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logsGroupByCreate).not.toHaveBeenCalled()
+
+ configLogic.actions.setGroupBys([
+ { key: 'service.name', source: 'resource' },
+ { key: 'severity_level', source: 'column' },
+ ])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logsGroupByCreate).toHaveBeenCalledTimes(1)
+ const body = (logsGroupByCreate as jest.Mock).mock.calls[0][1]
+ expect(body.query.groupBys).toEqual([
+ { key: 'service.name', source: 'resource' },
+ { key: 'severity_level', source: 'column' },
+ ])
+ expect(body.query.groupBy).toBeUndefined()
+ })
+})
diff --git a/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
index 766e23b0577f..a9d6e0fd3865 100644
--- a/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
+++ b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
@@ -31,7 +31,7 @@ const EMPTY_RESPONSE: _LogsGroupByResponseApi = {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsGroupByLogicValues {
- groupBy: LogsViewerGroupBy | null // logsViewerConfigLogic
+ groupBys: LogsViewerGroupBy[] // logsViewerConfigLogic
filters: LogsViewerFilters // logsViewerFiltersLogic
queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
utcDateRange: {
@@ -49,8 +49,21 @@ export interface logsGroupByLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsGroupByLogicActions {
- setGroupBy: (groupBy: LogsViewerGroupBy | null) => {
- groupBy: LogsViewerGroupBy | null
+ addGroupBy: (groupBy: LogsViewerGroupBy) => {
+ groupBy: LogsViewerGroupBy
+ } // logsViewerConfigLogic
+ removeGroupByAt: (index: number) => {
+ index: number
+ } // logsViewerConfigLogic
+ replaceGroupByAt: (
+ index: number,
+ groupBy: LogsViewerGroupBy
+ ) => {
+ groupBy: LogsViewerGroupBy
+ index: number
+ } // logsViewerConfigLogic
+ setGroupBys: (groupBys: LogsViewerGroupBy[]) => {
+ groupBys: LogsViewerGroupBy[]
} // logsViewerConfigLogic
setDateRange: (dateRange: DateRange) => {
dateRange: DateRange
@@ -134,7 +147,7 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
logsViewerFiltersLogic({ id: props.id }),
['filters', 'utcDateRange', 'queryFilterGroup'],
logsViewerConfigLogic({ id: props.id }),
- ['groupBy'],
+ ['groupBys'],
],
actions: [
logsViewerFiltersLogic({ id: props.id }),
@@ -149,7 +162,7 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
'setPinnedFilters',
],
logsViewerConfigLogic({ id: props.id }),
- ['setGroupBy'],
+ ['setGroupBys', 'addGroupBy', 'removeGroupByAt', 'replaceGroupByAt'],
],
})),
@@ -163,7 +176,7 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
{
loadGroups: async (debounceMs: number = 0, breakpoint) => {
await breakpoint(debounceMs)
- if (!values.groupBy) {
+ if (values.groupBys.length === 0) {
return EMPTY_RESPONSE
}
return await logsGroupByCreate(String(values.currentTeamId), {
@@ -176,8 +189,7 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
// filters from an embedded viewer, so a scoped viewer can't aggregate
// project-wide logs.
filterGroup: values.queryFilterGroup as unknown as _LogPropertyFilterApi[],
- groupBy: values.groupBy.key,
- groupBySource: values.groupBy.source,
+ groupBys: values.groupBys,
orderGroupsBy: values.orderGroupsBy,
},
})
@@ -228,8 +240,11 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
setFilters: reload,
setFilterGroup: reload,
setPinnedFilters: reload,
- // Immediate: switching the grouping key or ranking column is a deliberate click.
- setGroupBy: () => actions.loadGroups(),
+ // Immediate: changing the grouping dimensions or ranking column is a deliberate click.
+ setGroupBys: () => actions.loadGroups(),
+ addGroupBy: () => actions.loadGroups(),
+ removeGroupByAt: () => actions.loadGroups(),
+ replaceGroupByAt: () => actions.loadGroups(),
setOrderGroupsBy: () => actions.loadGroups(),
}
}),
diff --git a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
index 1cdd3f6c3de6..1393823755de 100644
--- a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { Fragment } from 'react'
import { IconChevronLeft, IconChevronRight } from '@posthog/icons'
import { LemonButton, LemonSegmentedButton, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
@@ -11,7 +12,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'
import { logsGroupByLogic } from 'products/logs/frontend/components/LogsGroupBy/logsGroupByLogic'
import { logsPatternsLogic } from 'products/logs/frontend/components/LogsPatterns/logsPatternsLogic'
-import { logsViewerConfigLogic } from './config/logsViewerConfigLogic'
+import { MAX_GROUP_BY_DIMENSIONS, logsViewerConfigLogic } from './config/logsViewerConfigLogic'
import { resolveGroupBySource } from './groupBySource'
import { LogsViewerToolbar } from './LogsViewerToolbar'
@@ -40,8 +41,8 @@ export const LogsDisplayBar = ({
showFacetRailToggle = false,
totalLogsCount,
}: LogsDisplayBarProps): JSX.Element => {
- const { facetRailCollapsed, viewMode, groupBy } = useValues(logsViewerConfigLogic)
- const { setFacetRailCollapsed, setViewMode, setGroupBy } = useActions(logsViewerConfigLogic)
+ const { facetRailCollapsed, viewMode } = useValues(logsViewerConfigLogic)
+ const { setFacetRailCollapsed, setViewMode } = useActions(logsViewerConfigLogic)
const showPatternsView = useFeatureFlag('LOGS_PATTERNS_VIEW')
const showGroupBy = useFeatureFlag('LOGS_GROUP_BY')
@@ -78,43 +79,7 @@ export const LogsDisplayBar = ({
options={viewModeOptions}
/>
)}
- {inGroupByMode && (
- <TaxonomicStringPopover
- size="small"
- groupType={TaxonomicFilterGroupType.Logs}
- groupTypes={[
- TaxonomicFilterGroupType.Logs,
- TaxonomicFilterGroupType.LogAttributes,
- TaxonomicFilterGroupType.LogResourceAttributes,
- ]}
- // `message` is not a grouping key — high-cardinality free text is the
- // Patterns lens's job, and the backend can't aggregate by it. Excluding it
- // from the Logs group drops the message-search item; excluding it from
- // LogAttributes keeps a `message contains …` search from leaking back in via
- // the Recent tab (message searches are recorded under LogAttributes).
- excludedProperties={{
- [TaxonomicFilterGroupType.Logs]: ['message'],
- [TaxonomicFilterGroupType.LogAttributes]: ['message'],
- }}
- value={groupBy?.key}
- onChange={(value, groupType) =>
- // Clearing the key keeps you in the Group view (empty state) — leaving
- // the view is the segmented bar's job, not the picker's. The source is
- // resolved from the key so a recent (recorded under LogAttributes) still
- // groups by the right top-level column instead of a missing attribute.
- setGroupBy(value ? { key: value, source: resolveGroupBySource(value, groupType) } : null)
- }
- allowClear
- placeholder="Group by"
- renderValue={(value) => (
- <span>
- Group by <span className="font-mono">{value}</span>
- </span>
- )}
- selectingKeyOnly
- data-attr="logs-group-by-picker"
- />
- )}
+ {inGroupByMode && <GroupByDimensionPickers />}
{inPatternsMode ? (
<PatternsCountIndicator id={id} />
) : inGroupByMode ? (
@@ -135,6 +100,103 @@ export const LogsDisplayBar = ({
)
}
+// `message` is not a grouping key — high-cardinality free text is the Patterns lens's job,
+// and the backend can't aggregate by it. Excluding it from the Logs group drops the
+// message-search item; excluding it from LogAttributes keeps a `message contains …` search
+// from leaking back in via the Recent tab (message searches are recorded under LogAttributes).
+const BASE_EXCLUDED_KEYS = ['message']
+
+/**
+ * Group mode's configuration: one picker pill per dimension, joined by "and", plus a
+ * trailing "+ and" affordance to add another (up to MAX_GROUP_BY_DIMENSIONS). Clearing a
+ * pill removes its dimension; clearing the last one returns the Group view's empty state —
+ * leaving the view is the segmented bar's job, not the picker's.
+ */
+const GroupByDimensionPickers = (): JSX.Element => {
+ const { groupBys } = useValues(logsViewerConfigLogic)
+ const { addGroupBy, removeGroupByAt, replaceGroupByAt } = useActions(logsViewerConfigLogic)
+
+ // A dimension's identity is (source, key), and the reducer allows the same key from
+ // different sources (resource `env` and log `env` are distinct combinations). So exclude a
+ // key from a tab only when picking it there would resolve to a source that's already used —
+ // re-picking that exact (source, key) would duplicate a dimension or silently no-op (the
+ // reducer guards both), but the cross-source combination stays available.
+ const excludedForPill = (pillIndex: number | null): Partial<Record<TaxonomicFilterGroupType, string[]>> => {
+ const used = groupBys.filter((_, i) => i !== pillIndex)
+ const usedKeysForTab = (groupType: TaxonomicFilterGroupType): string[] =>
+ used.filter((d) => resolveGroupBySource(d.key, groupType) === d.source).map((d) => d.key)
+ return {
+ [TaxonomicFilterGroupType.Logs]: [...BASE_EXCLUDED_KEYS, ...usedKeysForTab(TaxonomicFilterGroupType.Logs)],
+ [TaxonomicFilterGroupType.LogAttributes]: [
+ ...BASE_EXCLUDED_KEYS,
+ ...usedKeysForTab(TaxonomicFilterGroupType.LogAttributes),
+ ],
+ [TaxonomicFilterGroupType.LogResourceAttributes]: usedKeysForTab(
+ TaxonomicFilterGroupType.LogResourceAttributes
+ ),
+ }
+ }
+
+ const pickerProps = {
+ size: 'small' as const,
+ groupType: TaxonomicFilterGroupType.Logs,
+ groupTypes: [
+ TaxonomicFilterGroupType.Logs,
+ TaxonomicFilterGroupType.LogAttributes,
+ TaxonomicFilterGroupType.LogResourceAttributes,
+ ],
+ selectingKeyOnly: true,
+ }
+
+ return (
+ <>
+ {groupBys.map((dimension, index) => (
+ <Fragment key={`${dimension.source}:${dimension.key}`}>
+ {index > 0 && <span className="text-muted text-xs font-semibold uppercase">and</span>}
+ <TaxonomicStringPopover
+ {...pickerProps}
+ excludedProperties={excludedForPill(index)}
+ value={dimension.key}
+ onChange={(value, groupType) =>
+ // The source is resolved from the key so a recent (recorded under
+ // LogAttributes) still groups by the right top-level column instead
+ // of a missing attribute.
+ value
+ ? replaceGroupByAt(index, {
+ key: value,
+ source: resolveGroupBySource(value, groupType),
+ })
+ : removeGroupByAt(index)
+ }
+ allowClear
+ placeholder="Group by"
+ renderValue={(value) => (
+ <span>
+ {index === 0 ? 'Group by ' : ''}
+ <span className="font-mono">{value}</span>
+ </span>
+ )}
+ data-attr="logs-group-by-picker"
+ />
+ </Fragment>
+ ))}
+ {groupBys.length > 0 && groupBys.length < MAX_GROUP_BY_DIMENSIONS && (
+ <TaxonomicStringPopover
+ {...pickerProps}
+ type="tertiary"
+ excludedProperties={excludedForPill(null)}
+ value={undefined}
+ onChange={(value, groupType) =>
+ value && addGroupBy({ key: value, source: resolveGroupBySource(value, groupType) })
+ }
+ placeholder="+ and"
+ data-attr="logs-group-by-add-dimension"
+ />
+ )}
+ </>
+ )
+}
+
/**
* Patterns mode's contextual-right tools: the Compare toggle and its baseline picker. Lives in
* the display bar's right slot (like the Logs toolbar) rather than inside the results region,
diff --git a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.test.ts b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.test.ts
index e95ed93c771d..44624ac06ef6 100644
--- a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.test.ts
@@ -3,7 +3,7 @@ import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
import { FilterLogicalOperator } from '~/types'
-import { logsViewerConfigLogic } from './logsViewerConfigLogic'
+import { LogsViewerGroupBy, logsViewerConfigLogic } from './logsViewerConfigLogic'
import { LogsViewerFilters } from './types'
describe('logsViewerConfigLogic', () => {
@@ -64,6 +64,44 @@ describe('logsViewerConfigLogic', () => {
})
})
+ describe('groupBys', () => {
+ // The reducer, not the picker UI, is what guarantees the group-by API never sees a
+ // combination it rejects (cap of 4, no duplicate dimensions).
+ const dim = (key: string, source: LogsViewerGroupBy['source'] = 'log'): LogsViewerGroupBy => ({
+ key,
+ source,
+ })
+
+ it('appends in order and ignores additions past the cap', () => {
+ for (const key of ['a', 'b', 'c', 'd', 'e']) {
+ logic.actions.addGroupBy(dim(key))
+ }
+ expect(logic.values.groupBys.map((d) => d.key)).toEqual(['a', 'b', 'c', 'd'])
+ })
+
+ it('ignores a duplicate dimension but allows the same key from another source', () => {
+ logic.actions.addGroupBy(dim('env', 'resource'))
+ logic.actions.addGroupBy(dim('env', 'resource'))
+ logic.actions.addGroupBy(dim('env', 'log'))
+ expect(logic.values.groupBys).toEqual([dim('env', 'resource'), dim('env', 'log')])
+ })
+
+ it('removes by index preserving order of the rest', () => {
+ logic.actions.setGroupBys([dim('a'), dim('b'), dim('c')])
+ logic.actions.removeGroupByAt(1)
+ expect(logic.values.groupBys.map((d) => d.key)).toEqual(['a', 'c'])
+ })
+
+ it('replaces in place and ignores a replacement that duplicates another dimension', () => {
+ logic.actions.setGroupBys([dim('a'), dim('b')])
+ logic.actions.replaceGroupByAt(0, dim('c'))
+ expect(logic.values.groupBys.map((d) => d.key)).toEqual(['c', 'b'])
+
+ logic.actions.replaceGroupByAt(0, dim('b'))
+ expect(logic.values.groupBys.map((d) => d.key)).toEqual(['c', 'b'])
+ })
+ })
+
describe('sparklineCollapsed', () => {
it('defaults to false', () => {
expect(logic.values.sparklineCollapsed).toBe(false)
diff --git a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts
index 1f26a3500baf..0f83755744ac 100644
--- a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts
@@ -46,6 +46,10 @@ export interface LogsViewerGroupBy {
source: LogsGroupBySourceEnumApi
}
+// Mirrors the endpoint's MAX_GROUP_DIMENSIONS (group_by_query_runner.py) — the picker must
+// not offer a combination the API would reject.
+export const MAX_GROUP_BY_DIMENSIONS = 4
+
export interface LogsViewerConfigProps {
id: string
}
@@ -59,7 +63,7 @@ export interface logsViewerConfigLogicValues {
customColumns: string[] | undefined
facetRailCollapsed: boolean
filters: LogsViewerFilters
- groupBy: LogsViewerGroupBy | null
+ groupBys: LogsViewerGroupBy[]
orderBy: LogsOrderBy
sparklineBreakdownBy: LogsSparklineBreakdownBy
sparklineCollapsed: boolean
@@ -71,6 +75,9 @@ export interface logsViewerConfigLogicActions {
addColumn: (column: LogsColumnConfig) => {
column: LogsColumnConfig
}
+ addGroupBy: (groupBy: LogsViewerGroupBy) => {
+ groupBy: LogsViewerGroupBy
+ }
moveColumn: (
id: string,
direction: 'left' | 'right'
@@ -81,6 +88,16 @@ export interface logsViewerConfigLogicActions {
removeColumn: (id: string) => {
id: string
}
+ removeGroupByAt: (index: number) => {
+ index: number
+ }
+ replaceGroupByAt: (
+ index: number,
+ groupBy: LogsViewerGroupBy
+ ) => {
+ groupBy: LogsViewerGroupBy
+ index: number
+ }
setBaselineMode: (mode: PatternsBaselineMode) => {
mode: PatternsBaselineMode
}
@@ -110,8 +127,8 @@ export interface logsViewerConfigLogicActions {
setFilters: (filters: LogsViewerFilters) => {
filters: LogsViewerFilters
}
- setGroupBy: (groupBy: LogsViewerGroupBy | null) => {
- groupBy: LogsViewerGroupBy | null
+ setGroupBys: (groupBys: LogsViewerGroupBy[]) => {
+ groupBys: LogsViewerGroupBy[]
}
setOrderBy: (
orderBy: LogsOrderBy,
@@ -163,7 +180,10 @@ export const logsViewerConfigLogic = kea<logsViewerConfigLogicType>([
toggleSparklineCollapsed: true,
setFacetRailCollapsed: (facetRailCollapsed: boolean) => ({ facetRailCollapsed }),
setViewMode: (viewMode: LogsViewerViewMode) => ({ viewMode }),
- setGroupBy: (groupBy: LogsViewerGroupBy | null) => ({ groupBy }),
+ setGroupBys: (groupBys: LogsViewerGroupBy[]) => ({ groupBys }),
+ addGroupBy: (groupBy: LogsViewerGroupBy) => ({ groupBy }),
+ removeGroupByAt: (index: number) => ({ index }),
+ replaceGroupByAt: (index: number, groupBy: LogsViewerGroupBy) => ({ index, groupBy }),
setCompareEnabled: (enabled: boolean) => ({ enabled }),
setBaselineMode: (mode: PatternsBaselineMode) => ({ mode }),
@@ -222,7 +242,7 @@ export const logsViewerConfigLogic = kea<logsViewerConfigLogicType>([
],
// Compare state lives here (not in logsPatternsLogic) so the choice survives
// Logs↔Patterns switches within a visit — the patterns logic unmounts when leaving
- // the lens. Not persisted, like viewMode and groupBy.
+ // the lens. Not persisted, like viewMode and groupBys.
compareEnabled: [
false,
{
@@ -256,14 +276,28 @@ export const logsViewerConfigLogic = kea<logsViewerConfigLogicType>([
},
},
],
- // The Group view's configuration: which key to group by (behind the logs-group-by flag).
- // Kept separate from viewMode so the key survives switching lenses within a visit —
- // Logs and back returns to the same grouping. null = no key chosen yet (empty state).
- // Not persisted across visits — grouping is an explicit, per-visit exploration like Patterns.
- groupBy: [
- null as LogsViewerGroupBy | null,
+ // The Group view's configuration: the ordered dimensions to group by (behind the
+ // logs-group-by flag). Kept separate from viewMode so the choice survives switching
+ // lenses within a visit — Logs and back returns to the same grouping. Empty = no key
+ // chosen yet (empty state). Not persisted across visits — grouping is an explicit,
+ // per-visit exploration like Patterns.
+ groupBys: [
+ [] as LogsViewerGroupBy[],
{
- setGroupBy: (_, { groupBy }) => groupBy,
+ setGroupBys: (_, { groupBys }) => groupBys,
+ // Cap and duplicate guards live here, not in the UI: the picker disables
+ // in-use keys and hides the add affordance at the cap, but the reducer is
+ // what guarantees the API never sees a combination it would reject.
+ addGroupBy: (state, { groupBy }) =>
+ state.length >= MAX_GROUP_BY_DIMENSIONS ||
+ state.some((d) => d.key === groupBy.key && d.source === groupBy.source)
+ ? state
+ : [...state, groupBy],
+ removeGroupByAt: (state, { index }) => state.filter((_, i) => i !== index),
+ replaceGroupByAt: (state, { index, groupBy }) =>
+ state.some((d, i) => i !== index && d.key === groupBy.key && d.source === groupBy.source)
+ ? state
+ : state.map((d, i) => (i === index ? groupBy : d)),
},
],
}),