: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
fix(metrics): chart histogram metrics as bucket percentiles by default (#116674)
Daniel Visca80e5f9b1f005
diff --git a/products/metrics/frontend/components/MetricsOperations.test.tsx b/products/metrics/frontend/components/MetricsOperations.test.tsxnew file mode 100644index 000000000000..d9a02a6fbdf5--- /dev/null+++ b/products/metrics/frontend/components/MetricsOperations.test.tsx@@ -0,0 +1,45 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render } from '@testing-library/react'++import { initKeaTests } from '~/test/init'++import { OtelMetricTypeEnumApi } from 'products/metrics/frontend/generated/api.schemas'++import { MetricsOperations } from './MetricsOperations'+import { MetricAggregation } from './metricsViewerLogic'++describe('MetricsOperations', () => {+ beforeEach(() => initKeaTests())++ afterEach(() => cleanup())++ const optionsInAggregationMenu = (+ aggregation: MetricAggregation,+ selectedMetricType: OtelMetricTypeEnumApi | null+ ): string[] => {+ const { container } = render(+ <MetricsOperations+ clause={{ rangeFunction: null, aggregation, selectedMetricType }}+ onRangeFunctionChange={() => {}}+ onAggregationChange={() => {}}+ disabledReason={null}+ />+ )+ fireEvent.click(container.querySelector('[data-attr="metrics-operation-aggregation"]')!)+ return Array.from(document.querySelectorAll('[data-attr^="metrics-operation-option-"]')).map((option) =>+ option.getAttribute('data-attr')!.replace('metrics-operation-option-', '')+ )+ }++ // A PromQL histogram percentile converted to the builder has no metric type until the picker loads.+ it.each<[string, MetricAggregation, OtelMetricTypeEnumApi | null, boolean]>([+ ['a histogram metric', 'histogram_p95', OtelMetricTypeEnumApi.Histogram, true],+ ['a converted histogram percentile without a metric type', 'histogram_p95', null, true],+ ['a gauge', 'sum', OtelMetricTypeEnumApi.Gauge, false],+ ])('offers histogram percentiles for %s: %s', (_name, aggregation, selectedMetricType, offered) => {+ const options = optionsInAggregationMenu(aggregation, selectedMetricType)+ expect(options.includes('histogram_p99')).toBe(offered)+ expect(options).toContain('sum')+ })+})diff --git a/products/metrics/frontend/components/MetricsOperations.tsx b/products/metrics/frontend/components/MetricsOperations.tsxindex d8b24088819f..8e4db7a999f8 100644--- a/products/metrics/frontend/components/MetricsOperations.tsx+++ b/products/metrics/frontend/components/MetricsOperations.tsx@@ -1,7 +1,13 @@import { IconPlusSmall, IconX } from '@posthog/icons'import { LemonButton, LemonMenu, LemonMenuItem } from '@posthog/lemon-ui'-import { MetricAggregation, MetricRangeFunction, MetricsViewerClause } from './metricsViewerLogic'+import {+ MetricAggregation,+ MetricRangeFunction,+ MetricsViewerClause,+ isHistogramQuantileAggregation,+ supportsHistogramQuantile,+} from './metricsViewerLogic'interface OperationOption<T extends string> {value: T@@ -31,6 +37,34 @@ const AGGREGATION_OPTIONS: OperationOption<MetricAggregation>[] = [{ value: 'p95', label: 'p95', description: '95th percentile across the series.' },]+const HISTOGRAM_AGGREGATION_OPTIONS: OperationOption<MetricAggregation>[] = [+ {+ value: 'histogram_p50',+ label: 'Histogram p50',+ description: 'Median of the recorded values, read from the histogram buckets.',+ },+ {+ value: 'histogram_p95',+ label: 'Histogram p95',+ description: '95th percentile of the recorded values, read from the histogram buckets.',+ },+ {+ value: 'histogram_p99',+ label: 'Histogram p99',+ description: '99th percentile of the recorded values, read from the histogram buckets.',+ },+]++// A clause converted from a PromQL histogram percentile has no metric type, so its current+// aggregation also unlocks the other percentiles.+const aggregationOptionsFor = (+ metricType: MetricsViewerClause['selectedMetricType'],+ aggregation: MetricAggregation | null+): OperationOption<MetricAggregation>[] =>+ supportsHistogramQuantile(metricType) || isHistogramQuantileAggregation(aggregation)+ ? [...HISTOGRAM_AGGREGATION_OPTIONS, ...AGGREGATION_OPTIONS]+ : AGGREGATION_OPTIONS+function operationMenuItems<T extends string>(options: OperationOption<T>[],current: T | null,@@ -93,14 +127,18 @@ export function MetricsOperations({onAggregationChange,disabledReason,}: {- clause: Pick<MetricsViewerClause, 'rangeFunction' | 'aggregation'>+ clause: Pick<MetricsViewerClause, 'rangeFunction' | 'aggregation' | 'selectedMetricType'>onRangeFunctionChange: (rangeFunction: MetricRangeFunction | null) => voidonAggregationChange: (aggregation: MetricAggregation | null) => voiddisabledReason: string | null}): JSX.Element {- const { rangeFunction, aggregation } = clause+ const { rangeFunction, aggregation, selectedMetricType } = clause+ const aggregationOptions = aggregationOptionsFor(selectedMetricType, aggregation)const rangeFunctionOption = RANGE_FUNCTION_OPTIONS.find((option) => option.value === rangeFunction)- const aggregationOption = AGGREGATION_OPTIONS.find((option) => option.value === aggregation)+ // A saved or linked histogram percentile still shows its chip while the type is not known yet.+ const aggregationOption = [...HISTOGRAM_AGGREGATION_OPTIONS, ...AGGREGATION_OPTIONS].find(+ (option) => option.value === aggregation+ )return (<div className="flex flex-wrap items-center gap-1" data-attr="metrics-operations">@@ -119,7 +157,7 @@ export function MetricsOperations({{aggregationOption && (<OperationChiplabel={aggregationOption.label}- options={AGGREGATION_OPTIONS}+ options={aggregationOptions}current={aggregationOption.value}onPick={onAggregationChange}onRemove={() => onAggregationChange(null)}@@ -136,7 +174,7 @@ export function MetricsOperations({},{title: 'Aggregations',- items: operationMenuItems(AGGREGATION_OPTIONS, aggregation, onAggregationChange),+ items: operationMenuItems(aggregationOptions, aggregation, onAggregationChange),},]}>diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.tsindex 80d468855913..60c13a9f52a1 100644--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts@@ -317,7 +317,10 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([// value can already differ if it changed while the save was in flight.const savedQuery = savedInsight.query as MetricsQuery | undefinedposthog.capture('metrics insight saved', {- aggregation: viewerAggregationFromNode(savedQuery?.clauses?.[0]?.aggregation),+ aggregation: viewerAggregationFromNode(+ savedQuery?.clauses?.[0]?.aggregation,+ savedQuery?.clauses?.[0]?.quantile+ ),range_function: savedQuery?.clauses?.[0]?.rangeFunction ?? null,clause_count: savedQuery?.clauses?.length ?? null,has_formula: !!savedQuery?.formula,diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex f369a780aa52..7f9d83ce1ba1 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -28,7 +28,13 @@ import {} from 'products/metrics/frontend/generated/api'import { metricNamePickerLogic } from './metricNamePickerLogic'-import { createViewerClause, isBuilderCompatibleQuery, metricsViewerLogic, resolveDate } from './metricsViewerLogic'+import {+ MetricRangeFunction,+ createViewerClause,+ isBuilderCompatibleQuery,+ metricsViewerLogic,+ resolveDate,+} from './metricsViewerLogic'jest.mock('products/metrics/frontend/generated/api', () => ({...jest.requireActual('products/metrics/frontend/generated/api'),@@ -101,16 +107,18 @@ describe('metricsViewerLogic', () => {})// Regression: the builder used to pick an aggregation from the metric type. An unaggregated- // clause must stay one line per series, whatever the metric is.- it.each(['requests_total', 'queue_depth', 'request_duration'])(- 'selecting %s leaves the clause without operations',- (metricName) => {- logic.actions.setMetricName(metricName)- expect(logic.values.aggregation).toBeNull()- expect(logic.values.rangeFunction).toBeNull()- expect(logic.values.queryPayload?.clauses?.[0]).toMatchObject({ aggregation: 'none' })- }- )+ // counter or gauge must stay one line per series. A histogram is the exception: its scalar+ // value is the running sum of observations, so only its buckets chart something useful.+ it.each<[string, string | null, Record<string, unknown>]>([+ ['requests_total', null, { aggregation: 'none' }],+ ['queue_depth', null, { aggregation: 'none' }],+ ['request_duration', 'histogram_p95', { aggregation: 'histogram_quantile', quantile: 0.95 }],+ ])('selecting %s applies aggregation %s', (metricName, expected, payloadFields) => {+ logic.actions.setMetricName(metricName)+ expect(logic.values.aggregation).toBe(expected)+ expect(logic.values.rangeFunction).toBeNull()+ expect(logic.values.queryPayload?.clauses?.[0]).toMatchObject(payloadFields)+ })it('keeps the operations when the metric changes', () => {logic.actions.setMetricName('requests_total')@@ -119,6 +127,41 @@ describe('metricsViewerLogic', () => {logic.actions.setMetricName('queue_depth')expect(logic.values.rangeFunction).toBe('rate')expect(logic.values.aggregation).toBe('max')+ logic.actions.setMetricName('request_duration')+ expect(logic.values.aggregation).toBe('max')+ })++ it.each<[string, string[], string | null]>([+ ['without a group-by', [], null],+ ['with a group-by', ['container'], 'sum'],+ ])(+ 'drops a histogram percentile when the metric changes to one without buckets, %s',+ (_name, groupBy, expected) => {+ logic.actions.setMetricName('request_duration')+ logic.actions.setGroupByKeys(groupBy)+ logic.actions.setMetricName('queue_depth')+ expect(logic.values.aggregation).toBe(expected)+ expect(logic.values.groupByKeys).toEqual(groupBy)+ }+ )++ // The backend rejects a histogram percentile after a range function, so the later pick replaces the earlier one.+ it.each<[string, () => void, string | null, string | null]>([+ [+ 'a histogram percentile after a range function',+ () => {+ logic.actions.setRangeFunction('rate')+ logic.actions.setAggregation('histogram_p99')+ },+ null,+ 'histogram_p99',+ ],+ ['a range function after a histogram percentile', () => logic.actions.setRangeFunction('rate'), 'rate', null],+ ])('picking %s drops the other operation', (_name, pick, rangeFunction, aggregation) => {+ logic.actions.setMetricName('request_duration')+ pick()+ expect(logic.values.rangeFunction).toBe(rangeFunction)+ expect(logic.values.aggregation).toBe(aggregation)})it('sends a range function without an aggregation as per-series rates', () => {@@ -141,12 +184,22 @@ describe('metricsViewerLogic', () => {expect(logic.values.groupByKeys).toEqual([])})- it('adds a sum aggregation when grouping a clause without one', () => {- logic.actions.setMetricName('queue_depth')- logic.actions.setGroupByKeys(['container'])- expect(logic.values.aggregation).toBe('sum')- expect(logic.values.groupByKeys).toEqual(['container'])- })+ it.each<[string, MetricRangeFunction | null, string]>([+ ['queue_depth', null, 'sum'],+ ['request_duration', null, 'histogram_p95'],+ ['request_duration', 'rate', 'sum'],+ ])(+ 'adds an aggregation when grouping %s with range function %s and no aggregation: %s',+ (metricName, rangeFunction, expected) => {+ logic.actions.setMetricName(metricName)+ logic.actions.setAggregation(null)+ logic.actions.setRangeFunction(rangeFunction)+ logic.actions.setGroupByKeys(['container'])+ expect(logic.values.aggregation).toBe(expected)+ expect(logic.values.rangeFunction).toBe(rangeFunction)+ expect(logic.values.groupByKeys).toEqual(['container'])+ }+ )it('keeps the chosen aggregation when grouping', () => {logic.actions.setMetricName('queue_depth')@@ -434,6 +487,16 @@ describe('metricsViewerLogic', () => {expect(logic.values.anomalyReport).toBeNull()})+ // The endpoint has no viewer shorthand: an unmapped value fails validation and the badge silently disappears.+ it('asks the anomaly badge for the histogram percentile the chart shows', () => {+ logic.actions.setMetricName('request_duration')+ expect(logic.values.anomalyQuery).toEqual({+ metricName: 'request_duration',+ aggregation: 'histogram_quantile',+ quantile: 0.95,+ })+ })+// Without an AbortController, a superseded characterize call keeps running server-side// after a newer one starts — this pins that the stale request is actually cancelled,// not just ignored client-side once it resolves.@@ -1002,6 +1065,23 @@ describe('metricsViewerLogic', () => {// query, merely opening edit mode would mark the insight as changed.it.each<[string, MetricsQuery]>([['builder', SAVED_QUERY],+ [+ 'builder histogram percentile',+ {+ kind: NodeKind.MetricsQuery,+ clauses: [+ {+ name: 'a',+ metricName: 'request_duration',+ aggregation: 'histogram_quantile',+ metricType: 'histogram',+ quantile: 0.99,+ groupBy: [{ key: 'container' }],+ },+ ],+ dateRange: { date_from: '-6h' },+ },+ ],['PromQL',{@@ -1122,7 +1202,10 @@ describe('isBuilderCompatibleQuery', () => {['a range function', queryWith({ aggregation: undefined, rangeFunction: 'rate' }), true],['p95', queryWith({ aggregation: 'quantile', quantile: 0.95 }), true],['another quantile', queryWith({ aggregation: 'quantile', quantile: 0.99 }), false],- ['histogram_quantile', queryWith({ aggregation: 'histogram_quantile', quantile: 0.95 }), false],+ ['histogram p50', queryWith({ aggregation: 'histogram_quantile', quantile: 0.5 }), true],+ ['histogram p95', queryWith({ aggregation: 'histogram_quantile', quantile: 0.95 }), true],+ ['histogram p99', queryWith({ aggregation: 'histogram_quantile', quantile: 0.99 }), true],+ ['another histogram quantile', queryWith({ aggregation: 'histogram_quantile', quantile: 0.9 }), false],['a scoped filter', queryWith({ filters: [{ key: 'k', op: 'eq', value: 'v', scope: 'resource' }] }), false],['a scoped group-by', queryWith({ groupBy: [{ key: 'k', scope: 'attribute' }] }), false],['auto scopes', queryWith({ filters: [{ key: 'k', op: 'eq', value: 'v', scope: 'auto' }] }), true],diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex 5afba95dec4e..2e8393b1ac42 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -70,8 +70,44 @@ import type { MetricsChartSeries } from './metricsSeries'// A derived type ((typeof METRIC_AGGREGATIONS)[number]) would keep these in sync, but// kea-typegen inlines derived unions into every consumer's generated block — keep the// named alias so those blocks stay stable.-export type MetricAggregation = 'sum' | 'avg' | 'count' | 'min' | 'max' | 'p95'-export const METRIC_AGGREGATIONS: MetricAggregation[] = ['sum', 'avg', 'count', 'min', 'max', 'p95']+export type HistogramQuantileAggregation = 'histogram_p50' | 'histogram_p95' | 'histogram_p99'+export type MetricAggregation = 'sum' | 'avg' | 'count' | 'min' | 'max' | 'p95' | HistogramQuantileAggregation+export const METRIC_AGGREGATIONS: MetricAggregation[] = [+ 'sum',+ 'avg',+ 'count',+ 'min',+ 'max',+ 'p95',+ 'histogram_p50',+ 'histogram_p95',+ 'histogram_p99',+]++/** Viewer shorthands for the API's `histogram_quantile`, which reads the bucket distribution. */+const HISTOGRAM_QUANTILES: Record<HistogramQuantileAggregation, number> = {+ histogram_p50: 0.5,+ histogram_p95: 0.95,+ histogram_p99: 0.99,+}+export const DEFAULT_HISTOGRAM_AGGREGATION: HistogramQuantileAggregation = 'histogram_p95'++export const isHistogramQuantileAggregation = (+ aggregation: string | null+): aggregation is HistogramQuantileAggregation =>+ !!aggregation && Object.prototype.hasOwnProperty.call(HISTOGRAM_QUANTILES, aggregation)++const histogramQuantileFields = (+ aggregation: HistogramQuantileAggregation+): { aggregation: 'histogram_quantile'; quantile: number } => ({+ aggregation: 'histogram_quantile',+ quantile: HISTOGRAM_QUANTILES[aggregation],+})++const histogramAggregationForQuantile = (quantile: number | undefined): HistogramQuantileAggregation | null =>+ (Object.keys(HISTOGRAM_QUANTILES) as HistogramQuantileAggregation[]).find(+ (aggregation) => HISTOGRAM_QUANTILES[aggregation] === quantile+ ) ?? null/** Applied to each series before any aggregation, like `rate()` and `increase()` in PromQL. */export type MetricRangeFunction = 'rate' | 'increase'@@ -129,7 +165,10 @@ export interface MetricsViewerClauseBackfill {// Request-body slices the viewer assembles; the window fields are added at fetch time.export type MetricsQueryRequestBody = Pick<_MetricQueryBodyApi, 'clauses' | 'formula' | 'interval'>-export type MetricsAnomalyRequestBody = Pick<_MetricAnomalyBodyApi, 'metricName' | 'aggregation' | 'filters'>+export type MetricsAnomalyRequestBody = Pick<+ _MetricAnomalyBodyApi,+ 'metricName' | 'aggregation' | 'quantile' | 'filters'+>// Mirrors the backend's MAX_CLAUSES_PER_QUERY.export const MAX_CLAUSES = 10@@ -191,6 +230,24 @@ const HISTOGRAM_METRIC_TYPES: readonly OtelMetricTypeEnumApi[] = [OtelMetricTypeEnumApi.ExponentialHistogram,OtelMetricTypeEnumApi.Summary,]+// Ingest keeps these types' bucket distribution apart from the scalar value, which holds the running+// sum of observations. Exponential histograms are left out: ingest stores each bucket's lower edge,+// and the backend quantile reads every bound as an upper edge.+const HISTOGRAM_QUANTILE_METRIC_TYPES: readonly OtelMetricTypeEnumApi[] = [OtelMetricTypeEnumApi.Histogram]++export const supportsHistogramQuantile = (metricType: OtelMetricTypeEnumApi | null): boolean =>+ !!metricType && HISTOGRAM_QUANTILE_METRIC_TYPES.includes(metricType)++// The backend rejects histogram_quantile together with a range function, so a clause with a range+// function never defaults to a histogram percentile.+const defaultsToHistogramQuantile = (+ metricType: OtelMetricTypeEnumApi | null,+ rangeFunction: MetricRangeFunction | null+): boolean => !rangeFunction && supportsHistogramQuantile(metricType)++// Grouping needs an aggregation to combine series, so a grouped clause falls back to sum, not to none.+const fallbackAggregation = (groupByKeys: string[]): MetricAggregation | null => (groupByKeys.length ? 'sum' : null)+// The anomaly badge characterizes the most recent slice of the selected window against the rest.const ANOMALY_WINDOW_FRACTION = 0.2export const LIVE_REFRESH_MS = 15_000@@ -293,12 +350,25 @@ export const nodeAggregationFields = (if (!aggregation) {return {}}- return aggregation === 'p95' ? { aggregation: 'quantile', quantile: 0.95 } : { aggregation }+ if (aggregation === 'p95') {+ return { aggregation: 'quantile', quantile: 0.95 }+ }+ return isHistogramQuantileAggregation(aggregation) ? histogramQuantileFields(aggregation) : { aggregation }}/** Inverse of `nodeAggregationFields`, for reading a saved node back in viewer vocabulary. */-export const viewerAggregationFromNode = (aggregation: MetricsQueryClause['aggregation'] | undefined): string | null =>- aggregation === 'quantile' ? 'p95' : (aggregation ?? null)+export const viewerAggregationFromNode = (+ aggregation: MetricsQueryClause['aggregation'] | undefined,+ quantile?: number+): string | null => {+ if (aggregation === 'quantile') {+ return 'p95'+ }+ if (aggregation === 'histogram_quantile') {+ return histogramAggregationForQuantile(quantile) ?? aggregation+ }+ return aggregation ?? null+}const clauseWithoutAggregation = (clause: MetricsViewerClause): Omit<_MetricClauseApi, 'aggregation'> => {const filters = metricFiltersForGroup(clause.filterGroup)@@ -317,7 +387,9 @@ const clauseWithoutAggregation = (clause: MetricsViewerClause): Omit<_MetricClau// The REST API defaults a missing aggregation to 'sum', so a clause without one sends 'none' explicitly.const clauseToApiClause = (clause: MetricsViewerClause): _MetricClauseApi => ({...clauseWithoutAggregation(clause),- aggregation: clause.aggregation ?? 'none',+ ...(isHistogramQuantileAggregation(clause.aggregation)+ ? histogramQuantileFields(clause.aggregation)+ : { aggregation: clause.aggregation ?? 'none' }),})// Built from the same base as the API clause so a new clause field cannot reach one payload and@@ -401,7 +473,9 @@ export const isBuilderCompatibleQuery = (query: MetricsQuery): boolean =>(!clause.aggregation ||isMetricAggregation(clause.aggregation) ||isMetricRangeFunction(clause.aggregation) ||- (clause.aggregation === 'quantile' && clause.quantile === 0.95)) &&+ (clause.aggregation === 'quantile' && clause.quantile === 0.95) ||+ (clause.aggregation === 'histogram_quantile' &&+ histogramAggregationForQuantile(clause.quantile) !== null)) &&(clause.filters ?? []).every((filter) => isAutoScope(filter.scope)) &&(clause.groupBy ?? []).every((groupBy) => isAutoScope(groupBy.scope)))@@ -409,7 +483,7 @@ export const isBuilderCompatibleQuery = (query: MetricsQuery): boolean =>const viewerClauseFromNode = (clause: MetricsQueryClause): MetricsViewerClause => {// Saved queries predating range functions hold `rate` or `increase` as the aggregation.const legacy = splitLegacyAggregation(clause.aggregation)- const aggregation = legacy.aggregation ?? viewerAggregationFromNode(clause.aggregation)+ const aggregation = legacy.aggregation ?? viewerAggregationFromNode(clause.aggregation, clause.quantile)return {name: clause.name,metricName: clause.metricName,@@ -952,24 +1026,56 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([// picker list arrives later). Not derived from the picker's `items` —// those are live search results, so typing a new search would wipe a// derived value and queries/saves would silently go untyped.+ // A histogram's scalar value is the running sum of observations, so a histogram clause+ // without operations charts a bucket percentile instead. A type without buckets cannot+ // keep a histogram percentile.setSelectedMetricType: (state, { metricType }) =>- withActiveClause(state, (clause) => ({ ...clause, selectedMetricType: metricType })),+ withActiveClause(state, (clause) => {+ if (metricType === clause.selectedMetricType) {+ return clause+ }+ let aggregation = clause.aggregation+ if (!aggregation && defaultsToHistogramQuantile(metricType, clause.rangeFunction)) {+ aggregation = DEFAULT_HISTOGRAM_AGGREGATION+ } else if (+ isHistogramQuantileAggregation(aggregation) &&+ !supportsHistogramQuantile(metricType)+ ) {+ aggregation = fallbackAggregation(clause.groupByKeys)+ }+ return { ...clause, selectedMetricType: metricType, aggregation }+ }),+ // The backend cannot apply a histogram percentile after a range function, so the later+ // of the two picks replaces the other.setAggregation: (state, { aggregation }) =>// Without an aggregation there is nothing to split by.withActiveClause(state, (clause) => ({...clause,aggregation,+ rangeFunction: isHistogramQuantileAggregation(aggregation) ? null : clause.rangeFunction,groupByKeys: aggregation ? clause.groupByKeys : [],})),setRangeFunction: (state, { rangeFunction }) =>- withActiveClause(state, (clause) => ({ ...clause, rangeFunction })),+ withActiveClause(state, (clause) => ({+ ...clause,+ rangeFunction,+ aggregation:+ rangeFunction && isHistogramQuantileAggregation(clause.aggregation)+ ? fallbackAggregation(clause.groupByKeys)+ : clause.aggregation,+ })),// Attribute keys to split the clause into one series each (e.g. ['service.name', 'env']).- // Grouping needs an aggregation to combine series, so default to sum when none is set.+ // Grouping needs an aggregation to combine series, so a clause without one gets a default.setGroupByKeys: (state, { groupByKeys }) =>withActiveClause(state, (clause) => ({...clause,groupByKeys,- aggregation: clause.aggregation ?? (groupByKeys.length ? 'sum' : null),+ aggregation:+ clause.aggregation ??+ (groupByKeys.length &&+ defaultsToHistogramQuantile(clause.selectedMetricType, clause.rangeFunction)+ ? DEFAULT_HISTOGRAM_AGGREGATION+ : fallbackAggregation(groupByKeys)),})),// The clause's UniversalFilters group; converted into backend matchers by `metricFiltersForGroup`.setFilterGroup: (state, { filterGroup }) =>@@ -1626,7 +1732,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([const filters = metricFiltersForGroup(clause.filterGroup)return {metricName: clause.metricName.trim(),- aggregation,+ ...(isHistogramQuantileAggregation(aggregation)+ ? histogramQuantileFields(aggregation)+ : { aggregation }),...(filters.length ? { filters } : {}),}},diff --git a/products/metrics/frontend/queryLanguages/convert.ts b/products/metrics/frontend/queryLanguages/convert.tsindex 88522e364617..65dcff153da8 100644--- a/products/metrics/frontend/queryLanguages/convert.ts+++ b/products/metrics/frontend/queryLanguages/convert.ts@@ -25,13 +25,16 @@ export const GENERIC_LOSS_ISSUE = 'Parts of the query will change.'// The aggregations the builder's clause rows can show (see isBuilderCompatibleQuery in metricsViewerLogic).const BUILDER_EDITOR_AGGREGATIONS = new Set(['sum', 'avg', 'count', 'min', 'max'])+const BUILDER_EDITOR_HISTOGRAM_QUANTILES = new Set([0.5, 0.95, 0.99])/** Parts of a builder query that the builder can chart but not show in its clause rows. */function builderEditorLimits(query: BuilderQuery): string[] {const limits: string[] = []for (const clause of query.clauses.map(normalizeClause)) {if (clause.aggregation === 'histogram_quantile') {- limits.push(`series ${clause.name} uses a histogram quantile`)+ if (clause.quantile === undefined || !BUILDER_EDITOR_HISTOGRAM_QUANTILES.has(clause.quantile)) {+ limits.push(`series ${clause.name} uses a histogram quantile`)+ }} else if (clause.aggregation &&!BUILDER_EDITOR_AGGREGATIONS.has(clause.aggregation) &&diff --git a/products/metrics/frontend/queryLanguages/queryLanguages.test.ts b/products/metrics/frontend/queryLanguages/queryLanguages.test.tsindex 5a3b003b330f..8f52e6c568f3 100644--- a/products/metrics/frontend/queryLanguages/queryLanguages.test.ts+++ b/products/metrics/frontend/queryLanguages/queryLanguages.test.ts@@ -748,7 +748,10 @@ describe('metrics query languages', () => {([, expected, kind]) =>expected &&kind === 'lossless' &&- expected.clauses.every((clause) => clause.aggregation !== 'histogram_quantile')+ expected.clauses.every(+ (clause) =>+ clause.aggregation !== 'histogram_quantile' || [0.5, 0.95, 0.99].includes(clause.quantile!)+ )))('switching %s to the builder and back is lossless', (text) => {const conversion = convertMetricsQuery(metricsQuery({ language: 'promql', promql: text }), 'builder')@@ -895,10 +898,10 @@ describe('metrics query languages', () => {'builder',],[- 'a histogram quantile, which the builder can chart but not edit',+ 'a histogram quantile without a builder percentile, which the builder can chart but not edit',metricsQuery({language: 'promql',- promql: 'histogram_quantile(0.5, sum by (le) (rate({"http.server.duration_bucket"})))',+ promql: 'histogram_quantile(0.9, sum by (le) (rate({"http.server.duration_bucket"})))',}),'builder',],