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.

feat(metrics): configurable metric charts that keep their settings (#90517)

Frank Hamand8315349e7e92
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 38005ce05997..5c0d65918982 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -37751,6 +37751,41 @@
"enum": ["resource", "attribute", "auto"],
"type": "string"
},
+ "MetricsAxisScale": {
+ "description": "Matches quill's `YAxisConfig.scale` verbatim, so no vocabulary translation is needed. Deliberately not `YAxisSettings['scale']` ('logarithmic') or `TrendsFilter['yAxisScaleType']` ('log10').",
+ "enum": ["linear", "log"],
+ "type": "string"
+ },
+ "MetricsDisplaySettings": {
+ "additionalProperties": false,
+ "description": "Presentation only. The query engine never reads this, and it's stripped from the result cache key, so changing any of it re-renders without re-running the query.",
+ "properties": {
+ "goalLines": {
+ "items": {
+ "$ref": "#/definitions/GoalLine"
+ },
+ "type": "array"
+ },
+ "statSummary": {
+ "$ref": "#/definitions/MetricsStatSummary",
+ "default": "latest",
+ "description": "`stat` display only: which summary the headline value shows."
+ },
+ "type": {
+ "$ref": "#/definitions/MetricsDisplayType",
+ "default": "line"
+ },
+ "yAxis": {
+ "$ref": "#/definitions/MetricsYAxisSettings"
+ }
+ },
+ "type": "object"
+ },
+ "MetricsDisplayType": {
+ "description": "How a metrics result is charted. `stat` is a single headline value plus sparkline, not a time series.",
+ "enum": ["line", "area", "bar", "stat"],
+ "type": "string"
+ },
"MetricsFilterOp": {
"enum": ["eq", "neq", "regex", "not_regex"],
"type": "string"
@@ -37773,6 +37808,10 @@
"$ref": "#/definitions/DateRange",
"description": "Defaults to the last 24 hours when omitted; dashboard date filters override it"
},
+ "display": {
+ "$ref": "#/definitions/MetricsDisplaySettings",
+ "description": "Chart presentation. A node without it renders as a line chart."
+ },
"formula": {
"description": "Arithmetic over clause aliases (e.g. \"a / b\"); when set, only the formula series are returned",
"type": "string"
@@ -37978,6 +38017,34 @@
"required": ["labels", "points"],
"type": "object"
},
+ "MetricsStatSummary": {
+ "description": "Which summary the `stat` display's headline value shows.",
+ "enum": ["latest", "average", "total"],
+ "type": "string"
+ },
+ "MetricsYAxisSettings": {
+ "additionalProperties": false,
+ "properties": {
+ "max": {
+ "description": "Pins the top of the axis; unset means automatic. Pinning both ends drops the automatic stretch that keeps an off-scale goal line on-plot.",
+ "type": "number"
+ },
+ "min": {
+ "description": "Pins the bottom of the axis; unset means automatic. Ignored while `startAtZero` is on.",
+ "type": "number"
+ },
+ "scale": {
+ "$ref": "#/definitions/MetricsAxisScale",
+ "default": "linear"
+ },
+ "startAtZero": {
+ "default": true,
+ "description": "When false the axis floats to the data range instead of starting at zero. Ignored on a logarithmic scale, and on the bar display, where a bar's length encodes magnitude from zero.",
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
"MinimalHedgehogConfig": {
"additionalProperties": false,
"properties": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index ab7437fdbb70..dbfeccfb5021 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -4589,6 +4589,42 @@ export interface MetricsQueryResponse extends AnalyticsQueryResponseBase {
}
export type CachedMetricsQueryResponse = CachedQueryResponse<MetricsQueryResponse>
+/** How a metrics result is charted. `stat` is a single headline value plus sparkline, not a time series. */
+export type MetricsDisplayType = 'line' | 'area' | 'bar' | 'stat'
+
+/** Matches quill's `YAxisConfig.scale` verbatim, so no vocabulary translation is needed.
+ * Deliberately not `YAxisSettings['scale']` ('logarithmic') or `TrendsFilter['yAxisScaleType']` ('log10'). */
+export type MetricsAxisScale = 'linear' | 'log'
+
+/** Which summary the `stat` display's headline value shows. */
+export type MetricsStatSummary = 'latest' | 'average' | 'total'
+
+export interface MetricsYAxisSettings {
+ /** @default linear */
+ scale?: MetricsAxisScale
+ /** When false the axis floats to the data range instead of starting at zero. Ignored on a
+ * logarithmic scale, and on the bar display, where a bar's length encodes magnitude from zero.
+ * @default true */
+ startAtZero?: boolean
+ /** Pins the bottom of the axis; unset means automatic. Ignored while `startAtZero` is on. */
+ min?: number
+ /** Pins the top of the axis; unset means automatic. Pinning both ends drops the automatic
+ * stretch that keeps an off-scale goal line on-plot. */
+ max?: number
+}
+
+/** Presentation only. The query engine never reads this, and it's stripped from the result cache
+ * key, so changing any of it re-renders without re-running the query. */
+export interface MetricsDisplaySettings {
+ /** @default line */
+ type?: MetricsDisplayType
+ goalLines?: GoalLine[]
+ yAxis?: MetricsYAxisSettings
+ /** `stat` display only: which summary the headline value shows.
+ * @default latest */
+ statSummary?: MetricsStatSummary
+}
+
export interface MetricsQuery extends DataNode<MetricsQueryResponse> {
kind: NodeKind.MetricsQuery
clauses: MetricsQueryClause[]
@@ -4598,6 +4634,8 @@ export interface MetricsQuery extends DataNode<MetricsQueryResponse> {
interval?: string
/** Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned */
formula?: string
+ /** Chart presentation. A node without it renders as a line chart. */
+ display?: MetricsDisplaySettings
}
export interface SessionEventsItem {
diff --git a/posthog/schema.py b/posthog/schema.py
index 41a9f1ca4f72..8f316491b762 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -189,8 +189,11 @@ from posthog.schema_enums import (
Metric as Metric,
MetricsAggregation as MetricsAggregation,
MetricsAttributeScope as MetricsAttributeScope,
+ MetricsAxisScale as MetricsAxisScale,
+ MetricsDisplayType as MetricsDisplayType,
MetricsFilterOp as MetricsFilterOp,
MetricsOtelType as MetricsOtelType,
+ MetricsStatSummary as MetricsStatSummary,
MetricSummary as MetricSummary,
MultipleBreakdownType as MultipleBreakdownType,
MultipleVariantHandling as MultipleVariantHandling,
@@ -2320,6 +2323,32 @@ class MetricsQuerySeries(BaseModel):
points: list[MetricsQueryPoint]
+class MetricsYAxisSettings(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ max: float | None = Field(
+ default=None,
+ description=(
+ "Pins the top of the axis; unset means automatic. Pinning both ends drops"
+ " the automatic stretch that keeps an off-scale goal line on-plot."
+ ),
+ )
+ min: float | None = Field(
+ default=None,
+ description=("Pins the bottom of the axis; unset means automatic. Ignored while `startAtZero` is on."),
+ )
+ scale: MetricsAxisScale | None = MetricsAxisScale.LINEAR
+ startAtZero: bool | None = Field(
+ default=True,
+ description=(
+ "When false the axis floats to the data range instead of starting at zero."
+ " Ignored on a logarithmic scale, and on the bar display, where a bar's"
+ " length encodes magnitude from zero."
+ ),
+ )
+
+
class MinimalHedgehogConfig(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -6137,6 +6166,19 @@ class MetricPropertyFilter(BaseModel):
value: list[str | float | bool] | str | float | bool | None = None
+class MetricsDisplaySettings(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ goalLines: list[GoalLine] | None = None
+ statSummary: MetricsStatSummary | None = Field(
+ default=MetricsStatSummary.LATEST,
+ description="`stat` display only: which summary the headline value shows.",
+ )
+ type: MetricsDisplayType | None = MetricsDisplayType.LINE
+ yAxis: MetricsYAxisSettings | None = None
+
+
class MetricsQueryClause(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -27355,6 +27397,10 @@ class MetricsQuery(BaseModel):
default=None,
description=("Defaults to the last 24 hours when omitted; dashboard date filters override it"),
)
+ display: MetricsDisplaySettings | None = Field(
+ default=None,
+ description="Chart presentation. A node without it renders as a line chart.",
+ )
formula: str | None = Field(
default=None,
description=('Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned'),
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 94e0ae401381..3f2aedd87414 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -3296,6 +3296,18 @@ class MetricsAttributeScope(StrEnum):
AUTO = "auto"
+class MetricsAxisScale(StrEnum):
+ LINEAR = "linear"
+ LOG = "log"
+
+
+class MetricsDisplayType(StrEnum):
+ LINE = "line"
+ AREA = "area"
+ BAR = "bar"
+ STAT = "stat"
+
+
class MetricsFilterOp(StrEnum):
EQ = "eq"
NEQ = "neq"
@@ -3311,6 +3323,12 @@ class MetricsOtelType(StrEnum):
SUMMARY = "summary"
+class MetricsStatSummary(StrEnum):
+ LATEST = "latest"
+ AVERAGE = "average"
+ TOTAL = "total"
+
+
class MultiQuestionFormFieldType(StrEnum):
TEXT = "text"
NUMBER = "number"
diff --git a/products/metrics/backend/hogql_queries/metrics_query_runner.py b/products/metrics/backend/hogql_queries/metrics_query_runner.py
index e299406c8abc..bbf70561ed62 100644
--- a/products/metrics/backend/hogql_queries/metrics_query_runner.py
+++ b/products/metrics/backend/hogql_queries/metrics_query_runner.py
@@ -87,6 +87,14 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):
"MetricsQuery composes one HogQL query per clause via the metrics facade; there is no single statement"
)
+ def get_cache_payload(self) -> dict:
+ payload = super().get_cache_payload()
+ # `display` is presentation only — `_to_request` never reads it, so it must not namespace
+ # the cache. Without this, adding a goal line re-runs every bucket in ClickHouse, and two
+ # tiles differing only in chart type would each hold their own entry.
+ payload["query"].pop("display", None)
+ return payload
+
def _query_date_range(self) -> QueryDateRange:
# explicitDate keeps second-granular windows intact; without it,
# QueryDateRange rounds date_to up to end of day.
diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.py
index d52907508786..cf0bc1c1f827 100644
--- a/products/metrics/backend/tests/test_metrics_query_runner.py
+++ b/products/metrics/backend/tests/test_metrics_query_runner.py
@@ -11,10 +11,13 @@ from parameterized import parameterized
from posthog.schema import (
DashboardFilter,
DateRange,
+ GoalLine,
+ MetricsDisplaySettings,
MetricsQuery,
MetricsQueryClause,
MetricsQueryFilter,
MetricsQueryGroupBy,
+ MetricsYAxisSettings,
)
from posthog.constants import AvailableFeature
@@ -215,3 +218,22 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert runner.query.dateRange is not None
assert runner.query.dateRange.date_from == "-7d"
assert runner.query.dateRange.date_to == "-1d"
+
+ def _cache_key_for(self, **kwargs) -> str:
+ return self._runner(
+ MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")], **kwargs)
+ ).get_cache_key()
+
+ @parameterized.expand(
+ [
+ ("chart_type", MetricsDisplaySettings(type="bar")),
+ ("goal_lines", MetricsDisplaySettings(goalLines=[GoalLine(label="SLO", value=99.9)])),
+ ("y_axis", MetricsDisplaySettings(yAxis=MetricsYAxisSettings(scale="log", min=10, max=100))),
+ ("stat_summary", MetricsDisplaySettings(type="stat", statSummary="average")),
+ ]
+ )
+ def test_display_settings_do_not_change_the_cache_key(self, _name: str, display: MetricsDisplaySettings) -> None:
+ assert self._cache_key_for(display=display) == self._cache_key_for()
+
+ def test_query_semantics_still_change_the_cache_key(self) -> None:
+ assert self._cache_key_for(dateRange=DateRange(date_from="-7d")) != self._cache_key_for()
diff --git a/products/metrics/frontend/components/MetricsChartSettings.tsx b/products/metrics/frontend/components/MetricsChartSettings.tsx
new file mode 100644
index 000000000000..a9dd61e72d9f
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsChartSettings.tsx
@@ -0,0 +1,146 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { IconGear, IconPlusSmall } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonLabel, LemonSelect, LemonSwitch, Popover } from '@posthog/lemon-ui'
+
+import { GoalLinesList } from 'lib/components/GoalLinesList'
+
+import { metricsViewerLogic } from './metricsViewerLogic'
+
+// An emptied number input reads as NaN, which the chart ignores while the settings count still
+// sees a value — so it has to become undefined for the bound to be clearable.
+const asBound = (value: number | undefined): number | undefined =>
+ typeof value === 'number' && isFinite(value) ? value : undefined
+
+export function MetricsChartSettings(): JSX.Element {
+ const { displayType, goalLines, yAxisSettings } = useValues(metricsViewerLogic)
+ const { addGoalLine, updateGoalLine, removeGoalLine, setYAxisSetting } = useActions(metricsViewerLogic)
+ const [open, setOpen] = useState(false)
+
+ const [minDraft, setMinDraft] = useState(yAxisSettings.min)
+ const [maxDraft, setMaxDraft] = useState(yAxisSettings.max)
+ useEffect(() => setMinDraft(yAxisSettings.min), [yAxisSettings.min])
+ useEffect(() => setMaxDraft(yAxisSettings.max), [yAxisSettings.max])
+
+ const isLog = yAxisSettings.scale === 'log'
+ // Bars encode magnitude as length from zero, so quill ignores both a floated baseline and pinned
+ // bounds on them. The settings stay persisted and apply again on a line or area chart.
+ const isBar = displayType === 'bar'
+ const beginsAtZero = yAxisSettings.startAtZero !== false
+ const rangeDisabledReason = isLog
+ ? 'Not available on a logarithmic scale'
+ : isBar
+ ? 'Not available on a bar chart'
+ : undefined
+ const minDisabledReason =
+ rangeDisabledReason ?? (beginsAtZero ? 'Turn off "Begin at zero" to set a minimum' : undefined)
+
+ // Counts the persisted settings, not the drafts — a bound of 0 is still a bound.
+ const changedCount =
+ goalLines.length +
+ (yAxisSettings.scale ? 1 : 0) +
+ (beginsAtZero ? 0 : 1) +
+ (yAxisSettings.min !== undefined ? 1 : 0) +
+ (yAxisSettings.max !== undefined ? 1 : 0)
+
+ return (
+ <Popover
+ visible={open}
+ onClickOutside={() => setOpen(false)}
+ placement="bottom-end"
+ overlay={
+ <div className="flex flex-col gap-3 p-2 w-72">
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Goal lines</LemonLabel>
+ <GoalLinesList
+ goalLines={goalLines}
+ updateGoalLine={updateGoalLine}
+ removeGoalLine={removeGoalLine}
+ />
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlusSmall />}
+ onClick={addGoalLine}
+ data-attr="metrics-add-goal-line"
+ className="self-start"
+ >
+ Add goal line
+ </LemonButton>
+ </div>
+ <div className="flex flex-col gap-2">
+ <LemonLabel>Y axis</LemonLabel>
+ <LemonSelect
+ size="small"
+ value={yAxisSettings.scale ?? 'linear'}
+ onChange={(value) => setYAxisSetting('scale', value === 'linear' ? undefined : value)}
+ options={[
+ { value: 'linear', label: 'Linear' },
+ { value: 'log', label: 'Logarithmic' },
+ ]}
+ data-attr="metrics-y-axis-scale"
+ />
+ <LemonSwitch
+ label="Begin at zero"
+ tooltip="When off, the axis starts just below your lowest value, so small changes are easier to see."
+ checked={beginsAtZero}
+ disabledReason={rangeDisabledReason}
+ onChange={(checked) => setYAxisSetting('startAtZero', checked ? undefined : false)}
+ data-attr="metrics-y-axis-start-at-zero"
+ />
+ <div className="flex gap-2">
+ <div className="flex-1 flex flex-col gap-1">
+ <LemonLabel>Minimum</LemonLabel>
+ <LemonInput
+ type="number"
+ size="small"
+ placeholder="Auto"
+ value={minDraft}
+ disabledReason={minDisabledReason}
+ onChange={setMinDraft}
+ // Commit on blur, not on change: a number input reads as empty
+ // mid-entry, so every keystroke would clear the bound.
+ onBlur={() => setYAxisSetting('min', asBound(minDraft))}
+ onPressEnter={() => setYAxisSetting('min', asBound(minDraft))}
+ data-attr="metrics-y-axis-min"
+ />
+ </div>
+ <div className="flex-1 flex flex-col gap-1">
+ <LemonLabel>Maximum</LemonLabel>
+ <LemonInput
+ type="number"
+ size="small"
+ placeholder="Auto"
+ value={maxDraft}
+ disabledReason={rangeDisabledReason}
+ onChange={setMaxDraft}
+ onBlur={() => setYAxisSetting('max', asBound(maxDraft))}
+ onPressEnter={() => setYAxisSetting('max', asBound(maxDraft))}
+ data-attr="metrics-y-axis-max"
+ />
+ </div>
+ </div>
+ <span className="text-xs text-secondary">
+ {yAxisSettings.min !== undefined && yAxisSettings.max !== undefined
+ ? 'Setting both bounds hides a goal line that falls outside them.'
+ : 'Leave blank for an automatic bound.'}
+ </span>
+ </div>
+ </div>
+ }
+ >
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconGear />}
+ onClick={() => setOpen(!open)}
+ active={open}
+ sideIcon={changedCount > 0 ? <span className="text-xs text-secondary">{changedCount}</span> : undefined}
+ data-attr="metrics-chart-settings"
+ >
+ Options
+ </LemonButton>
+ </Popover>
+ )
+}
diff --git a/products/metrics/frontend/components/MetricsSeriesChart.test.tsx b/products/metrics/frontend/components/MetricsSeriesChart.test.tsx
index 424f319d1aaf..46d6faf0c614 100644
--- a/products/metrics/frontend/components/MetricsSeriesChart.test.tsx
+++ b/products/metrics/frontend/components/MetricsSeriesChart.test.tsx
@@ -9,6 +9,7 @@ import {
hoverUntilTooltip,
} from '@posthog/quill-charts/testing'
+import type { MetricsDisplaySettings } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import type { MetricsExemplar } from './MetricsExemplarMarkers'
@@ -21,8 +22,12 @@ function seriesWith(labels: Record<string, string>, values: (number | null)[]):
return { labels, points: BUCKETS.map((time, i) => ({ time, value: values[i] })) }
}
-function renderChart(series: MetricsChartSeries[], exemplars?: MetricsExemplar[]): void {
- render(<MetricsSeriesChart series={series} fallbackName="http.requests" exemplars={exemplars} />)
+function renderChart(
+ series: MetricsChartSeries[],
+ exemplars?: MetricsExemplar[],
+ display?: MetricsDisplaySettings
+): void {
+ render(<MetricsSeriesChart series={series} fallbackName="http.requests" exemplars={exemplars} display={display} />)
}
describe('MetricsSeriesChart', () => {
@@ -62,6 +67,40 @@ describe('MetricsSeriesChart', () => {
expect(screen.getAllByTestId('metrics-exemplar-marker')).toHaveLength(1)
})
+ // `stat` is in the schema union but has no renderer yet, so it must degrade to a line chart
+ // rather than blanking a saved tile.
+ it.each([
+ ['renders no display as a line chart', undefined, 'line'],
+ ['renders the area display as a line chart', 'area' as const, 'line'],
+ ['renders the bar display as a bar chart', 'bar' as const, 'bar'],
+ ['degrades the unimplemented stat display to a line chart', 'stat' as const, 'line'],
+ ])('%s', (_name, type, expectedChart) => {
+ renderChart([seriesWith({ service: 'a' }, [1, 2, 3]), seriesWith({ service: 'b' }, [4, 5, 6])], undefined, {
+ type,
+ })
+
+ expect(getHogChart().seriesCount).toBe(2)
+ expect(screen.getByTestId(`hog-chart-timeseries-${expectedChart}-legend`)).toBeInTheDocument()
+ })
+
+ // The exemplar overlay reads the chart's layout context, which throws when it isn't nested
+ // under a chart provider — so a bar chart that forgot to pass children through is a hard crash.
+ it('keeps exemplar markers working on the bar display', () => {
+ renderChart(
+ [seriesWith({}, [1, 2, 3])],
+ [{ timeMs: Date.parse(BUCKETS[1]), onClick: jest.fn(), tooltipLabel: 'test exemplar' }],
+ { type: 'bar' }
+ )
+ expect(screen.getAllByTestId('metrics-exemplar-marker')).toHaveLength(1)
+ })
+
+ it('draws a goal line above the data', () => {
+ renderChart([seriesWith({}, [1, 2, 3])], undefined, {
+ goalLines: [{ label: 'SLO', value: 10 }],
+ })
+ expect(screen.getByText('SLO')).toBeInTheDocument()
+ })
+
// A null bucket is a non-representable aggregate. Charting it as 0 is the legacy behavior;
// dropping the point instead would silently shift every later value a bucket to the left.
it('charts a null bucket as zero rather than dropping the point', async () => {
diff --git a/products/metrics/frontend/components/MetricsSeriesChart.tsx b/products/metrics/frontend/components/MetricsSeriesChart.tsx
index c01e31055ec4..3ca517ca3cd1 100644
--- a/products/metrics/frontend/components/MetricsSeriesChart.tsx
+++ b/products/metrics/frontend/components/MetricsSeriesChart.tsx
@@ -3,6 +3,8 @@ import { useMemo } from 'react'
import {
type Series,
+ TimeSeriesBarChart,
+ type TimeSeriesBarChartConfig,
TimeSeriesLineChart,
type TimeSeriesLineChartConfig,
createXAxisTickCallback,
@@ -13,22 +15,34 @@ import { getColorVar } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'
+import type { MetricsDisplaySettings } from '~/queries/schema/schema-general'
+
+import { buildMetricsChartConfig } from './metricsChartConfig'
import { MetricsExemplarMarkers, type MetricsExemplar } from './MetricsExemplarMarkers'
import { formatSeriesName, type MetricsChartSeries, seriesColor } from './metricsSeries'
-/** Multi-series metric line chart, shared by the Viewer and the dashboard/insight tile. Every series
- * shares one time grid (the backend zero-fills), so the x-axis comes from the first series. */
+const AREA_FILL_OPACITY = 0.2
+
+/** Multi-series metric time-series chart, shared by the Viewer and the dashboard/insight tile. Every
+ * series shares one time grid (the backend zero-fills), so the x-axis comes from the first series.
+ *
+ * `display.type: 'stat'` is in the schema but has no renderer yet, so it falls through to a line
+ * chart rather than blanking the tile. */
export function MetricsSeriesChart({
series,
fallbackName,
+ display,
exemplars,
}: {
series: MetricsChartSeries[]
fallbackName: string
+ display?: MetricsDisplaySettings
exemplars?: MetricsExemplar[]
}): JSX.Element {
const { timezone } = useValues(teamLogic)
const theme = useChartTheme()
+ const isBar = display?.type === 'bar'
+ const isArea = display?.type === 'area'
const chartSeries = useMemo<Series[]>(
() =>
@@ -38,29 +52,41 @@ export function MetricsSeriesChart({
// A null value is a gap (non-representable aggregate); charted as 0 for now.
data: s.points.map((p) => p.value ?? 0),
color: getColorVar(seriesColor(index)),
+ ...(isArea ? { fill: { opacity: AREA_FILL_OPACITY } } : {}),
})),
- [series, fallbackName]
+ [series, fallbackName, isArea]
)
const labels = useMemo(() => (series[0]?.points ?? []).map((p) => p.time), [series])
- const config = useChartConfig<TimeSeriesLineChartConfig>(
- () => ({
- xAxis: { tickFormatter: createXAxisTickCallback({ allDays: labels, timezone }) },
- legend: { show: chartSeries.length > 1, interactive: true },
- tooltip: {
- placement: 'cursor',
- pinnable: true,
+ const sharedConfig = useChartConfig<TimeSeriesLineChartConfig>(
+ () =>
+ buildMetricsChartConfig({
+ display,
+ xAxis: { tickFormatter: createXAxisTickCallback({ allDays: labels, timezone }) },
+ seriesCount: chartSeries.length,
labelFormatter: (label: string) => dayjs(label).tz(timezone).format('D MMM YYYY HH:mm:ss'),
- },
- }),
- [labels, timezone, chartSeries.length]
+ }),
+ [labels, timezone, chartSeries.length, display]
)
+ const markers = exemplars?.length ? <MetricsExemplarMarkers exemplars={exemplars} /> : null
+
return (
<div className="relative flex h-full w-full min-h-0 flex-col">
- <TimeSeriesLineChart series={chartSeries} labels={labels} theme={theme} config={config}>
- {exemplars?.length ? <MetricsExemplarMarkers exemplars={exemplars} /> : null}
- </TimeSeriesLineChart>
+ {isBar ? (
+ <TimeSeriesBarChart
+ series={chartSeries}
+ labels={labels}
+ theme={theme}
+ config={sharedConfig as TimeSeriesBarChartConfig}
+ >
+ {markers}
+ </TimeSeriesBarChart>
+ ) : (
+ <TimeSeriesLineChart series={chartSeries} labels={labels} theme={theme} config={sharedConfig}>
+ {markers}
+ </TimeSeriesLineChart>
+ )}
</div>
)
}
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index 4987516911f3..94ff2a9dd5ff 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -31,6 +31,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'
import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'
import { urls } from 'scenes/urls'
+import type { MetricsDisplayType } from '~/queries/schema/schema-general'
import {
AccessControlLevel,
AccessControlResourceType,
@@ -45,6 +46,7 @@ import { traceUrl } from 'products/tracing/frontend/traceLinks'
import { getMetricsInsightEditorDisabledReason } from '../metricsAccess'
import { MetricNameFilter } from './MetricNameFilter'
import { metricNamePickerLogic } from './metricNamePickerLogic'
+import { MetricsChartSettings } from './MetricsChartSettings'
import { type MetricsExemplar } from './MetricsExemplarMarkers'
import { MetricsLogsSourceTag } from './MetricsLogsSourceTag'
import { MetricsRelatedMenu } from './MetricsRelatedMenu'
@@ -63,6 +65,13 @@ import {
RECOMMENDED_AGGREGATION_BY_TYPE,
} from './metricsViewerLogic'
+// `stat` is in the schema but has no renderer yet, so the picker doesn't offer it.
+const DISPLAY_TYPE_OPTIONS: { value: MetricsDisplayType; label: string }[] = [
+ { value: 'line', label: 'Line' },
+ { value: 'area', label: 'Area' },
+ { value: 'bar', label: 'Bar' },
+]
+
const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [
{ value: 'sum', label: 'Sum' },
{ value: 'avg', label: 'Average' },
@@ -134,6 +143,8 @@ export const MetricsViewer = (): JSX.Element => {
isAddToDashboardModalOpen,
hasMetricName,
hasResults,
+ displayType,
+ metricsDisplay,
} = useValues(logic)
const {
setMetricName,
@@ -148,6 +159,7 @@ export const MetricsViewer = (): JSX.Element => {
saveAsInsight,
addToDashboard,
closeAddToDashboardModal,
+ setDisplayType,
} = useActions(logic)
const { items: pickerItems } = useValues(pickerLogic)
const { traceExemplars, errorSpikes, showErrorSpikes } = useValues(metricsSamplesLogic)
@@ -318,6 +330,15 @@ export const MetricsViewer = (): JSX.Element => {
disabledReason={metricsViewerDisabledReason}
/>
<MetricsGroupByButton disabledReason={metricsViewerDisabledReason} />
+ <LemonSelect
+ size="small"
+ value={displayType}
+ options={DISPLAY_TYPE_OPTIONS}
+ onChange={setDisplayType}
+ data-attr="metrics-viewer-display-type"
+ disabledReason={metricsViewerDisabledReason}
+ />
+ <MetricsChartSettings />
<MetricsRelatedMenu />
{anomalyBadge && <MetricsAnomalyTag anomaly={anomalyBadge} />}
<MetricsLogsSourceTag metricName={metricName} />
@@ -391,6 +412,7 @@ export const MetricsViewer = (): JSX.Element => {
<MetricsSeriesChart
series={chartSeries}
fallbackName={metricName}
+ display={metricsDisplay}
exemplars={chartMarkers}
/>
) : !queryLoading ? (
diff --git a/products/metrics/frontend/components/metricsChartConfig.test.ts b/products/metrics/frontend/components/metricsChartConfig.test.ts
new file mode 100644
index 000000000000..bcab87362376
--- /dev/null
+++ b/products/metrics/frontend/components/metricsChartConfig.test.ts
@@ -0,0 +1,52 @@
+import type { XAxisConfig } from '@posthog/quill-charts'
+
+import type { MetricsDisplaySettings } from '~/queries/schema/schema-general'
+
+import { buildMetricsChartConfig } from './metricsChartConfig'
+
+const X_AXIS: XAxisConfig = {}
+
+const build = (
+ display: MetricsDisplaySettings | undefined,
+ seriesCount = 1
+): ReturnType<typeof buildMetricsChartConfig> =>
+ buildMetricsChartConfig({ display, xAxis: X_AXIS, seriesCount, labelFormatter: (l) => l })
+
+describe('metricsChartConfig', () => {
+ it('omits the settings keys entirely when a query carries no display', () => {
+ const config = build(undefined)
+
+ // Not `toBeUndefined()`: `useChartConfig` spreads quill's defaults under whatever keys are
+ // present, so an explicitly-undefined key would override them and change existing charts.
+ expect(config).not.toHaveProperty('yAxis')
+ expect(config).not.toHaveProperty('goalLines')
+ })
+
+ it('renames goal line fields onto the quill config', () => {
+ const config = build({
+ goalLines: [{ label: 'SLO', value: 99.9, borderColor: '#ff0000', position: 'start' }],
+ })
+
+ expect(config.goalLines).toEqual([
+ {
+ value: 99.9,
+ label: 'SLO',
+ color: '#ff0000',
+ labelPosition: 'start',
+ displayLabel: undefined,
+ displayIfCrossed: undefined,
+ },
+ ])
+ })
+
+ it('maps y-axis settings and keeps unset bounds off the config', () => {
+ const config = build({ yAxis: { scale: 'log', startAtZero: false, max: 100 } })
+
+ expect(config.yAxis).toEqual({ scale: 'log', startAtZero: false, max: 100 })
+ })
+
+ it('only shows the legend once there is more than one series', () => {
+ expect(build(undefined, 1).legend).toMatchObject({ show: false })
+ expect(build(undefined, 2).legend).toMatchObject({ show: true })
+ })
+})
diff --git a/products/metrics/frontend/components/metricsChartConfig.ts b/products/metrics/frontend/components/metricsChartConfig.ts
new file mode 100644
index 000000000000..1757aeda13d8
--- /dev/null
+++ b/products/metrics/frontend/components/metricsChartConfig.ts
@@ -0,0 +1,79 @@
+import type {
+ GoalLineConfig,
+ TimeSeriesBarChartConfig,
+ TimeSeriesLineChartConfig,
+ XAxisConfig,
+ YAxisConfig,
+} from '@posthog/quill-charts'
+
+import type { GoalLine, MetricsDisplaySettings, MetricsYAxisSettings } from '~/queries/schema/schema-general'
+
+/** The config keys metrics sets. `TimeSeriesLineChartConfig` and `TimeSeriesBarChartConfig` declare
+ * these identically, so one builder serves both charts. */
+export type MetricsChartConfig = Pick<
+ TimeSeriesLineChartConfig & TimeSeriesBarChartConfig,
+ 'xAxis' | 'yAxis' | 'goalLines' | 'legend' | 'tooltip'
+>
+
+/** Field rename from the persisted schema shape onto quill's. Product analytics has an equivalent
+ * mapper, but it maps its own `GoalLineLike` and lives across a product boundary we can't import
+ * over; promoting one copy into `lib/charts` is worth doing once a third caller appears. */
+function goalLineToConfig(line: GoalLine): GoalLineConfig {
+ return {
+ value: line.value,
+ label: line.label,
+ displayLabel: line.displayLabel,
+ color: line.borderColor,
+ labelPosition: line.position,
+ displayIfCrossed: line.displayIfCrossed,
+ }
+}
+
+function goalLinesToConfigs(goalLines: GoalLine[] | undefined): GoalLineConfig[] | undefined {
+ return goalLines?.length ? goalLines.map(goalLineToConfig) : undefined
+}
+
+function yAxisToConfig(yAxis: MetricsYAxisSettings | undefined): YAxisConfig | undefined {
+ if (!yAxis) {
+ return undefined
+ }
+ const config: YAxisConfig = {}
+ if (yAxis.scale) {
+ config.scale = yAxis.scale
+ }
+ if (yAxis.startAtZero !== undefined) {
+ config.startAtZero = yAxis.startAtZero
+ }
+ if (yAxis.min !== undefined) {
+ config.min = yAxis.min
+ }
+ if (yAxis.max !== undefined) {
+ config.max = yAxis.max
+ }
+ // An all-defaults object would still override quill's own defaults, so emit nothing.
+ return Object.keys(config).length > 0 ? config : undefined
+}
+
+export function buildMetricsChartConfig({
+ display,
+ xAxis,
+ seriesCount,
+ labelFormatter,
+}: {
+ display: MetricsDisplaySettings | undefined
+ xAxis: XAxisConfig
+ seriesCount: number
+ labelFormatter: (label: string) => string
+}): MetricsChartConfig {
+ const yAxis = yAxisToConfig(display?.yAxis)
+ const goalLines = goalLinesToConfigs(display?.goalLines)
+ return {
+ xAxis,
+ // Keys stay absent rather than explicitly undefined: `useChartConfig` filters undefined
+ // values out before spreading quill's defaults, so an emitted key would win over them.
+ ...(yAxis ? { yAxis } : {}),
+ ...(goalLines ? { goalLines } : {}),
+ legend: { show: seriesCount > 1, interactive: true },
+ tooltip: { placement: 'cursor', pinnable: true, labelFormatter },
+ }
+}
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
index 70f6b8222118..fb9ec154c923 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -219,6 +219,49 @@ describe('metricsViewerLogic', () => {
expect(insightsApi.create).toHaveBeenCalledTimes(2)
})
+ // Chart settings are presentation, but a tile configured differently is still a different
+ // tile. Excluding `display` from the reuse check (as the result cache correctly does) would
+ // silently give the second tile the first one's chart type.
+ it('add to dashboard saves a fresh insight after only the chart settings change', async () => {
+ jest.mocked(insightsApi.create).mockImplementation(
+ async (insight: any) => ({ id: 1, short_id: 'abc123', ...insight }) as any
+ )
+ logic.actions.setMetricName('queue_depth')
+ logic.actions.addToDashboard()
+ await expectLogic(logic).toDispatchActions(['openAddToDashboardModal'])
+
+ logic.actions.closeAddToDashboardModal()
+ logic.actions.setDisplayType('bar')
+ logic.actions.addToDashboard()
+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess', 'openAddToDashboardModal'])
+ expect(insightsApi.create).toHaveBeenCalledTimes(2)
+ })
+
+ it('carries the configured chart settings onto the saved node', () => {
+ logic.actions.setMetricName('queue_depth')
+ logic.actions.setDisplayType('bar')
+ logic.actions.addGoalLine()
+ logic.actions.updateGoalLine(0, 'value', 99.9)
+ logic.actions.updateGoalLine(0, 'label', 'SLO')
+ logic.actions.setYAxisSetting('scale', 'log')
+
+ expect(logic.values.metricsQueryNode?.display).toEqual({
+ type: 'bar',
+ goalLines: [{ label: 'SLO', value: 99.9 }],
+ yAxis: { scale: 'log' },
+ })
+ })
+
+ // Emptying a bound must clear it, not persist an explicit undefined that the chart ignores
+ // while the settings count still sees a value.
+ it('clears a y-axis bound rather than persisting an undefined', () => {
+ logic.actions.setMetricName('queue_depth')
+ logic.actions.setYAxisSetting('max', 100)
+ logic.actions.setYAxisSetting('max', undefined)
+
+ expect(logic.values.metricsQueryNode?.display).toBeUndefined()
+ })
+
// A failed add-to-dashboard save must not leave the flow armed: a later plain
// "Save as insight" success would unexpectedly pop the modal.
it('a later plain save does not open the modal after a failed add-to-dashboard save', async () => {
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 1e94233731dc..fe2d537d5df5 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -14,7 +14,16 @@ import { insightsApi } from 'scenes/insights/utils/api'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { MetricsQuery, MetricsQueryClause, MetricsQueryFilter, NodeKind } from '~/queries/schema/schema-general'
+import {
+ GoalLine,
+ MetricsDisplaySettings,
+ MetricsDisplayType,
+ MetricsQuery,
+ MetricsQueryClause,
+ MetricsQueryFilter,
+ MetricsYAxisSettings,
+ NodeKind,
+} from '~/queries/schema/schema-general'
import { QueryBasedInsightModel } from '~/types'
import { PropertyOperator, UniversalFilterValue, UniversalFiltersGroup } from '~/types'
@@ -78,6 +87,8 @@ export const RECOMMENDED_AGGREGATION_BY_TYPE: Record<string, MetricAggregation>
exponential_histogram: 'p95',
}
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'
export const NEW_QUERY_STARTED_ERROR_MESSAGE = 'A new metrics query started, canceling the previous one'
// A superseded or unmounted request rejects with an abort, not a real failure — never surface it as an error.
@@ -194,7 +205,9 @@ export interface metricsViewerLogicValues {
correlationServices: string[]
dateFrom: string | null
dateTo: string | null
+ displayType: MetricsDisplayType
filterGroup: UniversalFiltersGroup
+ goalLines: GoalLine[]
groupByKeys: string[]
groupBySearch: string
hasMetricName: boolean
@@ -203,6 +216,7 @@ export interface metricsViewerLogicValues {
lastSavedQueryNode: MetricsQuery | null
liveRefresh: boolean
metricName: string
+ metricsDisplay: MetricsDisplaySettings | undefined
metricsQueryNode: MetricsQuery | null
pendingAddToDashboard: boolean
queryAbortController: AbortController | null
@@ -215,6 +229,7 @@ export interface metricsViewerLogicValues {
savedInsightLoading: boolean
selectedMetricType: OtelMetricTypeEnumApi | null
selectedServices: string[]
+ yAxisSettings: MetricsYAxisSettings
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -235,6 +250,9 @@ export interface metricsViewerLogicActions {
setServices: (services: string[]) => {
services: string[]
} // metricNamePickerLogic
+ addGoalLine: () => {
+ value: true
+ }
addToDashboard: () => {
value: true
}
@@ -313,6 +331,9 @@ export interface metricsViewerLogicActions {
openAddToDashboardModal: () => {
value: true
}
+ removeGoalLine: (index: number) => {
+ index: number
+ }
saveAsInsight: () => any
saveAsInsightFailure: (
error: string,
@@ -337,6 +358,9 @@ export interface metricsViewerLogicActions {
setDateTo: (dateTo: string | null) => {
dateTo: string | null
}
+ setDisplayType: (displayType: MetricsDisplayType) => {
+ displayType: MetricsDisplayType
+ }
setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
filterGroup: UniversalFiltersGroup
}
@@ -364,12 +388,33 @@ export interface metricsViewerLogicActions {
setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => {
metricType: OtelMetricTypeEnumApi | null
}
+ setYAxisSetting: (
+ key: keyof MetricsYAxisSettings,
+ value: boolean | number | string | undefined
+ ) => {
+ key: keyof MetricsYAxisSettings
+ value: boolean | number | string | undefined
+ }
+ updateGoalLine: (
+ index: number,
+ key: keyof GoalLine,
+ value: boolean | number | string
+ ) => {
+ index: number
+ key: keyof GoalLine
+ value: boolean | number | string
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsViewerLogicMeta {
__keaTypeGenInternalSelectorTypes: {
hasMetricName: (metricName: string) => boolean
+ metricsDisplay: (
+ displayType: MetricsDisplayType,
+ goalLines: GoalLine[],
+ yAxisSettings: MetricsYAxisSettings
+ ) => MetricsDisplaySettings | undefined
metricsQueryNode: (
metricName: string,
aggregation: MetricAggregation,
@@ -377,7 +422,8 @@ export interface metricsViewerLogicMeta {
dateFrom: string | null,
dateTo: string | null,
groupByKeys: string[],
- queryFilters: _MetricFilterApi[]
+ queryFilters: _MetricFilterApi[],
+ metricsDisplay: MetricsDisplaySettings | undefined
) => MetricsQuery | null
queryFilters: (filterGroup: UniversalFiltersGroup) => _MetricFilterApi[]
selectedServices: (filterGroup: UniversalFiltersGroup) => string[]
@@ -425,6 +471,20 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
// action aborts the previous controller before storing the new one.
setQueryAbortController: (controller: AbortController | null) => ({ controller }),
cancelInProgressQuery: (controller: AbortController | null) => ({ controller }),
+ // Chart presentation. These ride along on the saved query node but never reach the query
+ // engine, so changing one re-renders without refetching.
+ setDisplayType: (displayType: MetricsDisplayType) => ({ displayType }),
+ addGoalLine: true,
+ updateGoalLine: (index: number, key: keyof GoalLine, value: string | number | boolean) => ({
+ index,
+ key,
+ value,
+ }),
+ removeGoalLine: (index: number) => ({ index }),
+ setYAxisSetting: (key: keyof MetricsYAxisSettings, value: number | string | boolean | undefined) => ({
+ key,
+ value,
+ }),
}),
reducers({
metricName: ['' as string, { setMetricName: (_, { metricName }) => metricName }],
@@ -469,6 +529,35 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
null as AbortController | null,
{ setQueryAbortController: (_, { controller }) => controller },
],
+ displayType: [
+ DEFAULT_DISPLAY_TYPE as MetricsDisplayType,
+ { setDisplayType: (_, { displayType }) => displayType },
+ ],
+ goalLines: [
+ [] as GoalLine[],
+ {
+ addGoalLine: (state) => [...state, { label: '', value: 0 }],
+ updateGoalLine: (state, { index, key, value }) =>
+ state.map((line, i) => (i === index ? { ...line, [key]: value } : line)),
+ removeGoalLine: (state, { index }) => state.filter((_, i) => i !== index),
+ },
+ ],
+ yAxisSettings: [
+ {} as MetricsYAxisSettings,
+ {
+ // An undefined value clears the setting rather than persisting an explicit
+ // undefined, so an emptied number input goes back to automatic.
+ setYAxisSetting: (state, { key, value }) => {
+ const next = { ...state }
+ if (value === undefined) {
+ delete next[key]
+ } else {
+ Object.assign(next, { [key]: value })
+ }
+ return next
+ },
+ },
+ ],
isAddToDashboardModalOpen: [
false,
{
@@ -741,6 +830,23 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
})),
selectors({
hasMetricName: [(s) => [s.metricName], (metricName: string) => metricName.trim().length > 0],
+ // Chart settings as they'd be persisted, with every default omitted — an all-defaults
+ // object would change the shape of newly-saved nodes for no gain.
+ metricsDisplay: [
+ (s) => [s.displayType, s.goalLines, s.yAxisSettings],
+ (
+ displayType: MetricsDisplayType,
+ goalLines: GoalLine[],
+ yAxisSettings: MetricsYAxisSettings
+ ): MetricsDisplaySettings | undefined => {
+ const display: MetricsDisplaySettings = {
+ ...(displayType !== DEFAULT_DISPLAY_TYPE ? { type: displayType } : {}),
+ ...(goalLines.length ? { goalLines } : {}),
+ ...(Object.keys(yAxisSettings).length ? { yAxis: yAxisSettings } : {}),
+ }
+ return Object.keys(display).length ? display : undefined
+ },
+ ],
// The viewer state as a `MetricsQuery` schema node — what "Save as insight"
// persists, so the saved tile re-runs exactly what the viewer shows.
// The REST viewer's 'p95' shorthand maps to the node's quantile aggregation.
@@ -753,6 +859,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
s.dateTo,
s.groupByKeys,
s.queryFilters,
+ s.metricsDisplay,
],
(
metricName: string,
@@ -761,7 +868,8 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
dateFrom: string | null,
dateTo: string | null,
groupByKeys: string[],
- queryFilters: _MetricFilterApi[]
+ queryFilters: _MetricFilterApi[],
+ metricsDisplay: MetricsDisplaySettings | undefined
): MetricsQuery | null => {
const trimmedName = metricName.trim()
if (!trimmedName) {
@@ -795,6 +903,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
date_from: dateFrom ?? DEFAULT_DATE_FROM,
...(dateTo ? { date_to: dateTo } : {}),
},
+ ...(metricsDisplay ? { display: metricsDisplay } : {}),
}
},
],
diff --git a/products/metrics/frontend/nodes/MetricsQueryNode.tsx b/products/metrics/frontend/nodes/MetricsQueryNode.tsx
index 965c3f4ac5c9..c45df347e087 100644
--- a/products/metrics/frontend/nodes/MetricsQueryNode.tsx
+++ b/products/metrics/frontend/nodes/MetricsQueryNode.tsx
@@ -1,5 +1,5 @@
import { BuiltLogic, LogicWrapper, useValues } from 'kea'
-import { useState } from 'react'
+import { useMemo, useState } from 'react'
import { SpinnerOverlay } from '@posthog/lemon-ui'
@@ -24,8 +24,17 @@ export function MetricsQueryNode(props: {
}): JSX.Element | null {
const { onData, loadPriority, dataNodeCollectionId } = props.context.insightProps ?? {}
const [key] = useState(() => `MetricsQueryNode.${uniqueNode++}`)
+ // `dataNodeLogic` deep-compares its query to decide whether to refetch. Its
+ // `ignoreVisualizationOnlyChanges` option doesn't help here — that only reaches
+ // `cleanInsightQuery`, which bails unless both sides are insight query nodes, and a
+ // `MetricsQuery` isn't one. So chart settings have to be kept out of the query it sees,
+ // or changing the chart type would re-run the ClickHouse query.
+ const dataQuery = useMemo(() => {
+ const { display: _display, ...rest } = props.query
+ return rest
+ }, [props.query])
const logic = dataNodeLogic({
- query: props.query,
+ query: dataQuery,
key,
cachedResults: props.cachedResults,
loadPriority,
@@ -43,7 +52,7 @@ export function MetricsQueryNode(props: {
return (
<div className="relative flex flex-col w-full h-full min-h-[200px]">
{hasPoints ? (
- <MetricsSeriesChart series={series} fallbackName={fallbackName} />
+ <MetricsSeriesChart series={series} fallbackName={fallbackName} display={props.query.display} />
) : !responseLoading ? (
<div className="flex-1 flex items-center justify-center text-secondary text-sm">
No data for this metric in the selected range.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fa3507615925..0b200a2e25fc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -43887,6 +43887,51 @@ export namespace Schemas {
quantile?: number | null;
}
+ export type MetricsStatSummary = typeof MetricsStatSummary[keyof typeof MetricsStatSummary];
+
+
+ export const MetricsStatSummary = {
+ Latest: 'latest',
+ Average: 'average',
+ Total: 'total',
+ } as const;
+
+ export type MetricsDisplayType = typeof MetricsDisplayType[keyof typeof MetricsDisplayType];
+
+
+ export const MetricsDisplayType = {
+ Line: 'line',
+ Area: 'area',
+ Bar: 'bar',
+ Stat: 'stat',
+ } as const;
+
+ export type MetricsAxisScale = typeof MetricsAxisScale[keyof typeof MetricsAxisScale];
+
+
+ export const MetricsAxisScale = {
+ Linear: 'linear',
+ Log: 'log',
+ } as const;
+
+ export interface MetricsYAxisSettings {
+ /** Pins the top of the axis; unset means automatic. Pinning both ends drops the automatic stretch that keeps an off-scale goal line on-plot. */
+ max?: number | null;
+ /** Pins the bottom of the axis; unset means automatic. Ignored while `startAtZero` is on. */
+ min?: number | null;
+ scale?: MetricsAxisScale | null;
+ /** When false the axis floats to the data range instead of starting at zero. Ignored on a logarithmic scale, and on the bar display, where a bar's length encodes magnitude from zero. */
+ startAtZero?: boolean | null;
+ }
+
+ export interface MetricsDisplaySettings {
+ goalLines?: GoalLine[] | null;
+ /** `stat` display only: which summary the headline value shows. */
+ statSummary?: MetricsStatSummary | null;
+ type?: MetricsDisplayType | null;
+ yAxis?: MetricsYAxisSettings | null;
+ }
+
export interface MetricsQueryPoint {
/** Bucket start, ISO 8601 */
time: string;
@@ -43933,6 +43978,8 @@ export namespace Schemas {
clauses: MetricsQueryClause[];
/** Defaults to the last 24 hours when omitted; dashboard date filters override it */
dateRange?: DateRange | null;
+ /** Chart presentation. A node without it renders as a line chart. */
+ display?: MetricsDisplaySettings | null;
/** Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned */
formula?: string | null;
/** Bucket size, one of: second, minute, minute_5, minute_15, hour, hour_6, day, week; auto-picked from the range when omitted */