: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(metrics): wire the heatmap display type to the histogram query in the viewer (#102481)
Daniel Visca2afe5eba2552
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 4df36b0df693..0a37bb305466 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -38263,6 +38263,10 @@"metricName": {"type": "string"},+ "metricType": {+ "$ref": "#/definitions/MetricsOtelType",+ "description": "Pins the OTel type, as on a MetricsQuery clause: one name can exist as more than one type, and the heatmap must grid only the distribution series."+ },"modifiers": {"$ref": "#/definitions/HogQLQueryModifiers","description": "Modifiers used when performing the query"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex beb6e1905728..42da5dbda274 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -4898,6 +4898,9 @@ export type CachedMetricsQueryResponse = CachedQueryResponse<MetricsQueryResponsexport interface MetricsHistogramQuery extends DataNode<MetricsHistogramQueryResponse> {kind: NodeKind.MetricsHistogramQuerymetricName: string+ /** Pins the OTel type, as on a MetricsQuery clause: one name can exist as more than one+ * type, and the heatmap must grid only the distribution series. */+ metricType?: MetricsOtelTypefilters?: MetricsQueryFilter[]/** Defaults to the last 24 hours when omitted; dashboard date filters override it */dateRange?: DateRangediff --git a/posthog/schema.py b/posthog/schema.pyindex a1885933dfa6..ff1094201222 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -28531,6 +28531,14 @@ class MetricsHistogramQuery(BaseModel):interval: str | None = Field(default=None, description="Bucket size; auto-picked from the range when omitted")kind: Literal["MetricsHistogramQuery"] = "MetricsHistogramQuery"metricName: str+ metricType: MetricsOtelType | None = Field(+ default=None,+ description=(+ "Pins the OTel type, as on a MetricsQuery clause: one name can exist as"+ " more than one type, and the heatmap must grid only the distribution"+ " series."+ ),+ )modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")response: MetricsHistogramQueryResponse | None = Nonetags: QueryLogTags | None = Nonediff --git a/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py b/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.pyindex 6ac021564b7e..d609c98763d9 100644--- a/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py+++ b/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py@@ -133,6 +133,9 @@ class MetricsHistogramQueryRunner(AnalyticsQueryRunner[MetricsHistogramQueryRespfilters=filters,interval=interval,quantile=0.5, # unused by the grid query; required by the constructor+ # One metric name can hold series of more than one OTel type; the+ # heatmap must grid only the distribution the viewer picked.+ metric_type=self.query.metricType.value if self.query.metricType else None,)except ValueError as exc:# The runner signals user errors (inverted range, too-wide span, unknowndiff --git a/products/metrics/backend/tests/test_metrics_histogram_query_runner.py b/products/metrics/backend/tests/test_metrics_histogram_query_runner.pyindex b69355cde2b3..9e6aba95b940 100644--- a/products/metrics/backend/tests/test_metrics_histogram_query_runner.py+++ b/products/metrics/backend/tests/test_metrics_histogram_query_runner.py@@ -28,11 +28,11 @@ class TestMetricsHistogramQueryRunner(ClickhouseTestMixin, APIBaseTest):self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)def _seed_histogram(self, points_with_counts, temporality="delta", bounds=None, **kwargs):+ kwargs.setdefault("metric_type", "histogram")for timestamp, counts in points_with_counts:seed_metric(team_id=self.team.id,metric_name="latency",- metric_type="histogram",aggregation_temporality=temporality,histogram_bounds=bounds or self.BOUNDS,histogram_counts=counts,@@ -86,6 +86,18 @@ class TestMetricsHistogramQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.bounds, [])self.assertEqual(response.counts, [])+ # The viewer latches the OTel type at pick time and sends it as `metricType` — the+ # runner must filter on it, or one metric name stored as two types (a histogram and+ # an exponential histogram) blends into one heatmap.+ def test_metric_type_filters_to_that_type(self):+ self._seed_histogram([(self.anchor, [10, 10, 10, 0])])+ self._seed_histogram([(self.anchor, [5, 5, 5, 0])], metric_type="exponential_histogram")++ response = self._run(metricType="exponential_histogram")++ second_minute = [response.counts[b][1] for b in range(len(self.BOUNDS))]+ self.assertEqual(second_minute, [5, 5, 5])+def test_rejects_mixed_bucket_layouts(self):self._seed_histogram([(self.anchor, [10, 0, 0, 0])], bounds=[0.1, 0.5, 1.0])self._seed_histogram([(self.anchor, [10, 0, 0, 0])], bounds=[0.2, 1.0, 2.0])diff --git a/products/metrics/frontend/components/MetricsViewer.test.tsx b/products/metrics/frontend/components/MetricsViewer.test.tsxindex f59f301006e2..bf5bde752a80 100644--- a/products/metrics/frontend/components/MetricsViewer.test.tsx+++ b/products/metrics/frontend/components/MetricsViewer.test.tsx@@ -4,6 +4,8 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/reimport userEvent from '@testing-library/user-event'import { Provider } from 'kea'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { insightsApi } from 'scenes/insights/utils/api'import { teamLogic } from 'scenes/teamLogic'@@ -18,6 +20,7 @@ import {metricsNamesRetrieve,} from 'products/metrics/frontend/generated/api'+import { metricNamePickerLogic } from './metricNamePickerLogic'import { MetricsGroupByButton } from './MetricsGroupByButton'import { MetricsViewer } from './MetricsViewer'import { metricsViewerLogic } from './metricsViewerLogic'@@ -52,14 +55,34 @@ describe('MetricsViewer', () => {[AccessControlResourceType.Insight]: AccessControlLevel.Editor,},} as AppContext- useMocks({ get: { '/api/environments/:team_id/dashboards/': { count: 0, results: [] } } })+ useMocks({+ get: { '/api/environments/:team_id/dashboards/': { count: 0, results: [] } },+ post: {+ // The generic query endpoint the heatmap's MetricsHistogramQuery runs against.+ '/api/environments/:team_id/query/': { times: [], bounds: [], counts: [] },+ },+ })initKeaTests()- jest.mocked(metricsNamesRetrieve).mockResolvedValue({ results: [] })+ // The picker list feeds each clause's latched OTel type; the heatmap option keys off it.+ jest.mocked(metricsNamesRetrieve).mockResolvedValue({+ results: [+ { name: 'queue_depth', metric_type: 'gauge' },+ { name: 'request_duration', metric_type: 'histogram' },+ { name: 'http.server.duration', metric_type: 'histogram' },+ ],+ })jest.mocked(metricsQueryCreate).mockResolvedValue({ results: [] })jest.mocked(metricsAttributesRetrieve).mockResolvedValue({ results: [], count: 0 })jest.mocked(insightsApi.create).mockResolvedValue(SAVED_INSIGHT as InsightModel)logic = metricsViewerLogic()logic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.METRICS_DASHBOARD_PANELS]: true })+ // Load the picker list so metric switches latch the OTel type (drives heatmap eligibility).+ metricNamePickerLogic.actions.loadItemsSuccess([+ { name: 'queue_depth', metric_type: 'gauge' },+ { name: 'request_duration', metric_type: 'histogram' },+ { name: 'http.server.duration', metric_type: 'histogram' },+ ] as any)})afterEach(() => {@@ -105,6 +128,47 @@ describe('MetricsViewer', () => {expect(logic.values.viewerClauses).toHaveLength(2)})+ // The heatmap option only makes sense for a distribution metric; the picker disables it+ // (with the reason as its tooltip) for gauges, counters, and multi-series/formula queries.+ it('disables the heatmap option for a non-histogram metric and enables it for a histogram', async () => {+ logic.actions.setMetricName('queue_depth') // a gauge+ render(+ <Provider>+ <MetricsViewer />+ </Provider>+ )++ const heatmapMenuItem = (): Element | null =>+ Array.from(document.querySelectorAll('[role="menuitem"]')).find((el) =>+ el.textContent?.includes('Heatmap')+ ) ?? null++ fireEvent.click(document.querySelector('[data-attr="metrics-viewer-display-type"]') as Element)+ expect(heatmapMenuItem()?.getAttribute('aria-disabled')).toBe('true')++ fireEvent.click(document.querySelector('[data-attr="metrics-viewer-display-type"]') as Element) // close+ logic.actions.setMetricName('request_duration') // a histogram+ fireEvent.click(document.querySelector('[data-attr="metrics-viewer-display-type"]') as Element)+ expect(heatmapMenuItem()?.getAttribute('aria-disabled')).not.toBe('true')+ })++ // Selecting the heatmap runs the histogram query and renders the grid, not the shared+ // time-series chart the other panels draw from.+ it('renders the histogram node when the heatmap display is selected on a histogram metric', async () => {+ logic.actions.setMetricName('request_duration')+ render(+ <Provider>+ <MetricsViewer />+ </Provider>+ )++ logic.actions.setDisplayType('heatmap')++ // The histogram endpoint returned an empty grid, so the node renders its empty state+ // rather than the time-series chart or the generic "no metric" prompt.+ expect(await screen.findByText('No data for this metric in the selected range.')).toBeInTheDocument()+ })+// "Add to dashboard" saves the query as an insight, then hands off to the shared dashboard// picker. That picker's "Add to a new dashboard" does nothing unless the create-dashboard// dialog is rendered alongside it, which is easy to leave out of a scene.diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 40620a27cc26..06ccd6633c82 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -30,6 +30,7 @@ import { AccessControlLevel, AccessControlResourceType, DateMappingOption } fromimport { traceUrl } from 'products/tracing/frontend/traceLinks'import { getMetricsInsightEditorDisabledReason } from '../metricsAccess'+import { MetricsHistogramQueryNode } from '../nodes/MetricsHistogramQueryNode'import { MetricsPanel } from '../panels/MetricsPanel'import { METRICS_PANELS } from '../panels/registry'import { MetricsAnomalyPanel } from './MetricsAnomalyPanel'@@ -46,7 +47,7 @@ import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'import { LIVE_REFRESH_MS, MAX_CLAUSES, metricsViewerLogic, sanitizeFormulaInput } from './metricsViewerLogic'const BASE_DISPLAY_TYPES: MetricsDisplayType[] = ['line', 'area', 'bar']-const PANEL_DISPLAY_TYPES: MetricsDisplayType[] = ['stat', 'gauge', 'bargauge', 'table']+const PANEL_DISPLAY_TYPES: MetricsDisplayType[] = ['stat', 'gauge', 'bargauge', 'table', 'heatmap']// Mirrors the curated set used by `LogsViewer/Filters/DateRangeFilter`.const DATE_OPTIONS: DateMappingOption[] = [@@ -110,6 +111,8 @@ export const MetricsViewer = (): JSX.Element => {hasResults,displayType,metricsDisplay,+ heatmapEligible,+ histogramQueryNode,} = useValues(logic)const {setDateFrom,@@ -136,14 +139,25 @@ export const MetricsViewer = (): JSX.Element => {// Gate on the result shape, not the clause edits: a formula result is ungrouped even// when its input clauses group, and a clause without a metric name never runs.const resultIsGrouped = chartSeries.some((s) => Object.keys(s.labels).length > 0)+ // The heatmap saves a MetricsHistogramQuery, but insight alerts only support MetricsQuery,+ // so alert creation would save a query the alerts page cannot validate.+ const isHeatmap = displayType === 'heatmap' && histogramQueryNode !== nullconst displayTypeOptions = useMemo(() => {const types = dashboardPanelsEnabled ? [...BASE_DISPLAY_TYPES, ...PANEL_DISPLAY_TYPES] : BASE_DISPLAY_TYPESreturn types.map((value) => {const def = METRICS_PANELS[value]- const disabledReason = def.needsGroupBy && !resultIsGrouped ? 'Add a group-by to use this panel' : undefined+ const disabledReason = def.needsGroupBy+ ? !resultIsGrouped+ ? 'Add a group-by to use this panel'+ : undefined+ : def.needsHistogram+ ? !heatmapEligible+ ? 'Pick a single histogram metric (no formula) to use this panel'+ : undefined+ : undefinedreturn { value, label: def.label, disabledReason }})- }, [dashboardPanelsEnabled, resultIsGrouped])+ }, [dashboardPanelsEnabled, resultIsGrouped, heatmapEligible])const { exemplarDotClicked } = useActions(metricsUsageTrackingLogic)const metricsViewerDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.Metrics,@@ -332,7 +346,12 @@ export const MetricsViewer = (): JSX.Element => {loading={savedInsightLoading}tooltip="Get notified when this metric crosses a threshold (uses insight alerts)"disabledReason={- insightEditorDisabledReason ?? (!hasMetricName ? 'Pick a metric first' : undefined)+ insightEditorDisabledReason ??+ (!hasMetricName+ ? 'Pick a metric first'+ : isHeatmap+ ? 'Alerts are not supported for the heatmap display'+ : undefined)}data-attr="metrics-viewer-create-alert">@@ -385,6 +404,13 @@ export const MetricsViewer = (): JSX.Element => {<div className="h-full flex items-center justify-center text-secondary text-sm">Pick a metric to see its time series.</div>+ ) : isHeatmap && histogramQueryNode ? (+ // The heatmap runs its own histogram query, so it mounts the histogram+ // node rather than consuming the time-series result the other panels share.+ // It comes before the error/loading branches: the shared time-series+ // request still runs for the samples panel, and its failure must not+ // mask an independently loaded histogram.+ <MetricsHistogramQueryNode query={histogramQueryNode} context={{}} />) : queryError ? (<div className="h-full flex items-center justify-center"><LemonBanner type="error" className="max-w-md">@@ -403,7 +429,7 @@ export const MetricsViewer = (): JSX.Element => {No data for this metric in the selected range.</div>) : null}- {queryLoading && <SpinnerOverlay />}+ {queryLoading && !isHeatmap && <SpinnerOverlay />}</div></div>{hasMetricName && (diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex d98c9208fcf3..1555534ae486 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -27,7 +27,7 @@ import {} from 'products/metrics/frontend/generated/api'import { metricNamePickerLogic } from './metricNamePickerLogic'-import { metricsViewerLogic, resolveDate } from './metricsViewerLogic'+import { createViewerClause, metricsViewerLogic, resolveDate } from './metricsViewerLogic'jest.mock('products/metrics/frontend/generated/api', () => ({...jest.requireActual('products/metrics/frontend/generated/api'),@@ -152,6 +152,113 @@ describe('metricsViewerLogic', () => {expect(logic.values.metricsQueryNode).toBeNull()})+ // A latency-over-time heatmap is only meaningful for a distribution metric — offering it+ // for a gauge or counter would render a meaningless all-in-one-bucket chart.+ it.each([+ ['request_duration', 'histogram', true],+ ['queue_depth', 'gauge', false],+ ['requests_total', 'sum', false],+ ])('heatmap eligibility for %s (%s) is %s', (metricName, _type, expected) => {+ logic.actions.setMetricName(metricName)+ expect(logic.values.heatmapEligible).toBe(expected)+ })++ // The heatmap reads a single distribution: a multi-series or formula query has no one+ // histogram to grid, so the option is ineligible there too.+ it('is not heatmap-eligible for multi-series or formula queries', () => {+ logic.actions.setMetricName('request_duration')+ expect(logic.values.heatmapEligible).toBe(true)++ logic.actions.setFormula('a / 2')+ expect(logic.values.heatmapEligible).toBe(false)+ logic.actions.setFormula('')++ logic.actions.addClause()+ logic.actions.setMetricName('queue_depth')+ expect(logic.values.heatmapEligible).toBe(false)+ })++ // The heatmap runs a MetricsHistogramQuery built from the same clause and window as the+ // time-series MetricsQuery, so the tile re-runs exactly what the viewer shows.+ it('maps the active histogram clause to a MetricsHistogramQuery node', () => {+ logic.actions.setMetricName('request_duration')+ logic.actions.setFilterGroup(+ filterGroupWith([{ key: 'namespace', operator: PropertyOperator.Exact, value: ['posthog'] }])+ )+ logic.actions.setDateFrom('-24h')++ expect(logic.values.histogramQueryNode).toEqual({+ kind: NodeKind.MetricsHistogramQuery,+ metricName: 'request_duration',+ metricType: 'histogram',+ filters: [{ key: 'namespace', op: 'eq', value: 'posthog' }],+ dateRange: { date_from: '-24h' },+ })+ })++ it('produces no MetricsHistogramQuery node when the query is not heatmap-eligible', () => {+ logic.actions.setMetricName('queue_depth')+ expect(logic.values.histogramQueryNode).toBeNull()+ })++ // "Save as insight" on the heatmap persists the histogram query node, not the time-series+ // node, so the saved tile renders the same heatmap the viewer showed.+ it('saves the histogram query node when the heatmap display is selected', () => {+ logic.actions.setMetricName('request_duration')+ logic.actions.setDisplayType('heatmap')++ expect(logic.values.savedQueryNode?.kind).toBe(NodeKind.MetricsHistogramQuery)+ expect(logic.values.metricsQueryNode?.kind).toBe(NodeKind.MetricsQuery)+ })++ // Mirrors the needsGroupBy fallback: a query that stops being heatmap-eligible (a metric+ // switch to a gauge, a formula added) cannot stay on a display type that no longer applies.+ it('falls back to the default display when the query stops being heatmap-eligible', () => {+ logic.actions.setMetricName('request_duration')+ logic.actions.setDisplayType('heatmap')+ expect(logic.values.displayType).toBe('heatmap')++ logic.actions.setMetricName('queue_depth')+ expect(logic.values.displayType).toBe('line')+ })++ // The heatmap grids one distribution as-is; the histogram query has no grouping field,+ // so a grouped clause would render its heatmap with the grouping silently dropped.+ it('is not heatmap-eligible for a grouped clause', () => {+ logic.actions.setMetricName('request_duration')+ logic.actions.setGroupByKeys(['container'])++ expect(logic.values.heatmapEligible).toBe(false)+ expect(logic.values.histogramQueryNode).toBeNull()+ })++ // The display latches only at metric-switch time, so every other change that makes the+ // query ineligible (a formula, a second clause, a URL restore, a group-by) must fall+ // back too — otherwise the viewer keeps "heatmap" selected while rendering a time+ // series, and saving silently does nothing (savedQueryNode is null).+ it('falls back to the default display from heatmap on any eligibility loss', () => {+ const expectHeatmapFallback = (act: () => void): void => {+ logic.actions.setClauses([createViewerClause('a')], '')+ logic.actions.setMetricName('request_duration')+ logic.actions.setDisplayType('heatmap')+ expect(logic.values.displayType).toBe('heatmap')++ act()+ expect(logic.values.displayType).toBe('line')+ }++ expectHeatmapFallback(() => logic.actions.setFormula('a / 2'))+ expectHeatmapFallback(() => {+ logic.actions.addClause()+ logic.actions.setMetricName('queue_depth')+ })+ expectHeatmapFallback(() => logic.actions.duplicateClause(0))+ expectHeatmapFallback(() => logic.actions.setGroupByKeys(['container']))+ expectHeatmapFallback(() =>+ logic.actions.setClauses([createViewerClause('a'), createViewerClause('b')], 'a / 2')+ )+ })+// Guards the multi-series save path: each clause carries its own metric/aggregation,// and the (sanitized) formula rides along — otherwise a saved insight re-runs a// different query than the viewer showed.diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex b49522fa8628..151f70941d5a 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -24,8 +24,10 @@ import {GoalLine,MetricsDisplaySettings,MetricsDisplayType,+ MetricsHistogramQuery,MetricsQuery,MetricsQueryClause,+ MetricsQueryFilter,MetricsYAxisSettings,NodeKind,} from '~/queries/schema/schema-general'@@ -168,6 +170,13 @@ export const RECOMMENDED_AGGREGATION_BY_TYPE: Record<string, MetricAggregation>export const DEFAULT_DATE_FROM = '-1h'// Kept off the persisted node: a saved query with no `display` renders as a line chart anyway.export const DEFAULT_DISPLAY_TYPE: MetricsDisplayType = 'line'+// A latency-over-time heatmap only makes sense for a distribution metric; gauges and+// counters have no per-bucket histogram to grid.+const HISTOGRAM_METRIC_TYPES: readonly OtelMetricTypeEnumApi[] = [+ OtelMetricTypeEnumApi.Histogram,+ OtelMetricTypeEnumApi.ExponentialHistogram,+ OtelMetricTypeEnumApi.Summary,+]// 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@@ -370,8 +379,10 @@ export interface metricsViewerLogicValues {groupBySearch: stringhasMetricName: booleanhasResults: boolean+ heatmapEligible: boolean+ histogramQueryNode: MetricsHistogramQuery | nullisAddToDashboardModalOpen: boolean- lastSavedQueryNode: MetricsQuery | null+ lastSavedQueryNode: MetricsHistogramQuery | MetricsQuery | nullliveRefresh: booleanmetricName: stringmetricsDisplay: MetricsDisplaySettings | undefined@@ -390,6 +401,7 @@ export interface metricsViewerLogicValues {queryState: MetricsViewerQueryStatesavedInsight: InsightModel | nullsavedInsightLoading: boolean+ savedQueryNode: MetricsHistogramQuery | MetricsQuery | nullselectedMetricType: OtelMetricTypeEnumApi | nullselectedServices: string[]viewerClauses: MetricsViewerClause[]@@ -580,8 +592,8 @@ export interface metricsViewerLogicActions {setGroupBySearch: (groupBySearch: string) => {groupBySearch: string}- setLastSavedQueryNode: (query: MetricsQuery) => {- query: MetricsQuery+ setLastSavedQueryNode: (query: MetricsHistogramQuery | MetricsQuery) => {+ query: MetricsHistogramQuery | MetricsQuery}setLiveRefresh: (liveRefresh: boolean) => {liveRefresh: boolean@@ -646,6 +658,18 @@ export interface metricsViewerLogicMeta {dateTo: string | null,metricsDisplay: MetricsDisplaySettings | undefined) => MetricsQuery | null+ heatmapEligible: (namedClauses: MetricsViewerClause[], formula: string) => boolean+ histogramQueryNode: (+ namedClauses: MetricsViewerClause[],+ heatmapEligible: boolean,+ dateFrom: string | null,+ dateTo: string | null+ ) => MetricsHistogramQuery | null+ savedQueryNode: (+ displayType: MetricsDisplayType,+ metricsQueryNode: MetricsQuery | null,+ histogramQueryNode: MetricsHistogramQuery | null+ ) => MetricsHistogramQuery | MetricsQuery | nullqueryFilters: (activeClause: MetricsViewerClause) => _MetricFilterApi[]selectedServices: (activeClause: MetricsViewerClause) => string[]correlationServices: (selectedServices: string[], queryResults: _MetricSeriesApi[]) => string[]@@ -712,7 +736,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([addToDashboard: true,openAddToDashboardModal: true,closeAddToDashboardModal: true,- setLastSavedQueryNode: (query: MetricsQuery) => ({ query }),+ setLastSavedQueryNode: (query: MetricsQuery | MetricsHistogramQuery) => ({ query }),// Saves the current query as an insight (reusing the last save while the query is// unchanged) and routes to its alerts page, where the shared insight-alert form// builds a MetricsAlertConfig on it. Surfaces insight alerts for metrics instead of@@ -897,7 +921,10 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([// the API may normalize the stored node (injected defaults, version// stamps), and a comparison against that would never match and would// save a duplicate insight on every click.- lastSavedQueryNode: [null as MetricsQuery | null, { setLastSavedQueryNode: (_, { query }) => query }],+ lastSavedQueryNode: [+ null as MetricsQuery | MetricsHistogramQuery | null,+ { setLastSavedQueryNode: (_, { query }) => query },+ ],// Armed while an addToDashboard-initiated save is in flight, so the success// path opens the modal instead of the "View insight" toast. Not reset on// success by a reducer — the success listener must still read it as armed.@@ -978,6 +1005,15 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([actions.setServices(values.selectedServices)}}+ // The heatmap display is valid only while the query stays eligible. Every change+ // that can end eligibility (a formula, a second clause, a group-by, a URL restore)+ // must fall back, or "heatmap" stays selected while the viewer renders a time+ // series and saving silently does nothing (savedQueryNode is null).+ const resetHeatmapIfIneligible = (): void => {+ if (values.displayType === 'heatmap' && !values.heatmapEligible) {+ actions.setDisplayType(DEFAULT_DISPLAY_TYPE)+ }+ }return {// A panel whose registry entry needs grouped data cannot stay selected once nothing// is grouped anymore — fall back rather than render it against a result shape it@@ -990,14 +1026,25 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([) {actions.setDisplayType(DEFAULT_DISPLAY_TYPE)}+ resetHeatmapIfIneligible()},+ setFormula: resetHeatmapIfIneligible,// `setFilterGroup` changes the active clause's chips; the clause-navigation// actions change which clause's chips are the scope.setFilterGroup: syncPickerServices,setActiveClauseIndex: syncPickerServices,- addClause: syncPickerServices,- removeClause: syncPickerServices,- duplicateClause: syncPickerServices,+ addClause: () => {+ syncPickerServices()+ resetHeatmapIfIneligible()+ },+ removeClause: () => {+ syncPickerServices()+ resetHeatmapIfIneligible()+ },+ duplicateClause: () => {+ syncPickerServices()+ resetHeatmapIfIneligible()+ },addAttributeFilter: ({ key, value }) => {const inner = values.filterGroup.values[0] as UniversalFiltersGroupconst existingIndex = inner.values.findIndex(@@ -1037,13 +1084,19 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([},setMetricName: ({ metricName }) => {const metricType = values.items.find((item) => item.name === metricName.trim())?.metric_type- actions.setSelectedMetricType(toKnownMetricType(metricType))+ const knownType = toKnownMetricType(metricType)+ actions.setSelectedMetricType(knownType)// Each metric type has one sensible default; a manual aggregation pick// holds only until the next metric switch.const recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefinedif (recommended && recommended !== values.aggregation) {actions.setRecommendedAggregation(recommended)}+ // A distribution metric leaving the chart can't keep the heatmap display —+ // fall back rather than render it against a metric with no histogram.+ if (values.displayType === 'heatmap' && (!knownType || !HISTOGRAM_METRIC_TYPES.includes(knownType))) {+ actions.setDisplayType(DEFAULT_DISPLAY_TYPE)+ }},loadItemsSuccess: backfillClauseTypes,// A URL restore replaces every clause at once and never ran the pick-time@@ -1051,17 +1104,18 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([setClauses: () => {backfillClauseTypes()syncPickerServices()+ resetHeatmapIfIneligible()},saveAsInsightFailure: ({ error }) => {lemonToast.error(`Failed to save insight: ${error}`)},addToDashboard: () => {- if (!canCreateMetricsInsight() || !values.metricsQueryNode) {+ if (!canCreateMetricsInsight() || !values.savedQueryNode) {return}// Re-clicking with an unchanged query reuses the saved insight instead// of littering saved insights with duplicates.- if (values.savedInsight && objectsEqual(values.lastSavedQueryNode, values.metricsQueryNode)) {+ if (values.savedInsight && objectsEqual(values.lastSavedQueryNode, values.savedQueryNode)) {actions.openAddToDashboardModal()return}@@ -1079,12 +1133,12 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([}},createAlert: () => {- if (!canCreateMetricsInsight() || !values.metricsQueryNode) {+ if (!canCreateMetricsInsight() || !values.savedQueryNode) {return}// Reuse the saved insight while the query is unchanged; route straight to its// alerts page since no save (and so no saveAsInsightSuccess) is coming.- if (values.savedInsight && objectsEqual(values.lastSavedQueryNode, values.metricsQueryNode)) {+ if (values.savedInsight && objectsEqual(values.lastSavedQueryNode, values.savedQueryNode)) {router.actions.push(urls.insightAlerts(values.savedInsight.short_id))return}@@ -1190,7 +1244,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([if (!canCreateMetricsInsight()) {return null}- const query = values.metricsQueryNode+ const query = values.savedQueryNodeif (!query) {return null}@@ -1384,6 +1438,57 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([}},],+ // The heatmap renders one distribution, so it needs exactly one non-formula clause on a+ // distribution metric. The OTel type is latched at pick time (backfilled from the picker+ // list), so this doesn't flicker as the live picker search results change.+ heatmapEligible: [+ (s) => [s.namedClauses, s.formula],+ (namedClauses: MetricsViewerClause[], formula: string): boolean =>+ namedClauses.length === 1 &&+ !formula &&+ namedClauses[0].groupByKeys.length === 0 &&+ namedClauses[0].selectedMetricType !== null &&+ HISTOGRAM_METRIC_TYPES.includes(namedClauses[0].selectedMetricType),+ ],+ // The viewer state as a `MetricsHistogramQuery` schema node — the heatmap's query, built+ // from the same clause and window as the time-series node so the tile re-runs exactly+ // what the viewer shows. Null while the query can't grid a distribution.+ histogramQueryNode: [+ (s) => [s.namedClauses, s.heatmapEligible, s.dateFrom, s.dateTo],+ (+ namedClauses: MetricsViewerClause[],+ heatmapEligible: boolean,+ dateFrom: string | null,+ dateTo: string | null+ ): MetricsHistogramQuery | null => {+ if (!heatmapEligible) {+ return null+ }+ const clause = namedClauses[0]+ const filters = metricFiltersForGroup(clause.filterGroup)+ return {+ kind: NodeKind.MetricsHistogramQuery,+ metricName: clause.metricName.trim(),+ ...(clause.selectedMetricType ? { metricType: clause.selectedMetricType } : {}),+ ...(filters.length ? { filters: filters as MetricsQueryFilter[] } : {}),+ dateRange: {+ date_from: dateFrom ?? DEFAULT_DATE_FROM,+ ...(dateTo ? { date_to: dateTo } : {}),+ },+ }+ },+ ],+ // What "Save as insight" / add-to-dashboard / create-alert persist and route on: the+ // histogram query while the heatmap display is selected, otherwise the time-series node.+ savedQueryNode: [+ (s) => [s.displayType, s.metricsQueryNode, s.histogramQueryNode],+ (+ displayType: MetricsDisplayType,+ metricsQueryNode: MetricsQuery | null,+ histogramQueryNode: MetricsHistogramQuery | null+ ): MetricsQuery | MetricsHistogramQuery | null =>+ displayType === 'heatmap' ? histogramQueryNode : metricsQueryNode,+ ],// The active clause's filter bar as backend matchers — what the samples panel sends.queryFilters: [(s) => [s.activeClause],diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ccd87f9ed141..cb69a03ba731 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -54338,6 +54338,8 @@ export namespace Schemas {interval?: string | null;kind?: 'MetricsHistogramQuery';metricName: string;+ /** Pins the OTel type, as on a MetricsQuery clause: one name can exist as more than one type, and the heatmap must grid only the distribution series. */+ metricType?: MetricsOtelType | null;/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;response?: MetricsHistogramQueryResponse | null;