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): add multi-series and formula support to the metrics viewer (#92049)

Jimmy Zhuf88c82cdff2e
diff --git a/posthog/tasks/alerts/test/test_metrics_alerts.py b/posthog/tasks/alerts/test/test_metrics_alerts.py
index 277c855a5a61..ff55d60800ef 100644
--- a/posthog/tasks/alerts/test/test_metrics_alerts.py
+++ b/posthog/tasks/alerts/test/test_metrics_alerts.py
@@ -86,14 +86,19 @@ class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):
self.metric_name = f"queue.depth.{self._testMethodName}"
def create_metrics_insight(
- self, group_by: Optional[list[str]] = None, clauses: Optional[list[dict[str, Any]]] = None
+ self,
+ group_by: Optional[list[str]] = None,
+ clauses: Optional[list[dict[str, Any]]] = None,
+ formula: Optional[str] = None,
) -> dict:
if clauses is None:
clause: dict[str, Any] = {"name": "a", "metricName": self.metric_name, "aggregation": "avg"}
if group_by:
clause["groupBy"] = [{"key": key} for key in group_by]
clauses = [clause]
- query_dict = {"kind": "MetricsQuery", "clauses": clauses}
+ query_dict: dict[str, Any] = {"kind": "MetricsQuery", "clauses": clauses}
+ if formula:
+ query_dict["formula"] = formula
return self.dashboard_api.create_insight(data={"name": "metrics insight", "query": query_dict})[1]
def create_alert(
@@ -203,6 +208,39 @@ class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):
breach_messages = mock_send_breaches.call_args.args[1]
assert any("big" in message for message in breach_messages), breach_messages
+ def test_formula_alert_evaluates_only_the_formula_series(
+ self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
+ ) -> None:
+ # Input clause 'a' (50) breaches the upper bound on its own; the formula result
+ # (a / b = 5) does not. Catches an extractor that evaluates the input clauses
+ # instead of the formula-only result the query returns.
+ divisor_metric = f"{self.metric_name}.divisor"
+ self.seed_gauge({6: 50.0, 7: 50.0})
+ seed_metric(
+ team_id=self.team.pk,
+ metric_name=divisor_metric,
+ metric_type="gauge",
+ points=[(dt.datetime(2026, 7, 1, hour, 30, tzinfo=dt.UTC), 10.0) for hour in (6, 7)],
+ labels={},
+ )
+ insight = self.create_metrics_insight(
+ clauses=[
+ {"name": "a", "metricName": self.metric_name, "aggregation": "avg"},
+ {"name": "b", "metricName": divisor_metric, "aggregation": "avg"},
+ ],
+ formula="a / b",
+ )
+ alert = self.create_alert(insight, upper=20.0)
+
+ run_alert_check(alert["id"])
+
+ updated_alert = AlertConfiguration.objects.get(pk=alert["id"])
+ assert updated_alert.state == AlertState.NOT_FIRING
+ alert_check = AlertCheck.objects.filter(alert_configuration=alert["id"]).latest("created_at")
+ assert alert_check.calculated_value == 5.0
+ assert alert_check.error is None
+ mock_send_breaches.assert_not_called()
+
def test_relative_increase_fires(
self, mock_send_breaches: MagicMock, mock_send_errors: MagicMock, mock_feature_enabled: MagicMock
) -> None:
diff --git a/products/metrics/backend/hogql_queries/metrics_query_runner.py b/products/metrics/backend/hogql_queries/metrics_query_runner.py
index bbf70561ed62..602f6c9353bc 100644
--- a/products/metrics/backend/hogql_queries/metrics_query_runner.py
+++ b/products/metrics/backend/hogql_queries/metrics_query_runner.py
@@ -21,6 +21,7 @@ from posthog.schema import (
)
from posthog.hogql import ast
+from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
@@ -143,7 +144,13 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):
def _calculate(self) -> MetricsQueryResponse:
self._enforce_alpha_gate_for_anonymous_viewers()
- series = run_metric_query(team=self.team, request=self._to_request())
+ try:
+ series = run_metric_query(team=self.team, request=self._to_request())
+ except ValueError as exc:
+ # The facade signals user errors (bad formula, unknown clause alias, bad
+ # quantile) with ValueError; /query only exposes typed errors, so a bare
+ # ValueError would surface as a 500 instead of a 400.
+ raise ExposedHogQLError(str(exc)) from exc
return MetricsQueryResponse(
results=[
MetricsQuerySeries(
diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.py
index cf0bc1c1f827..4fd27d995b97 100644
--- a/products/metrics/backend/tests/test_metrics_query_runner.py
+++ b/products/metrics/backend/tests/test_metrics_query_runner.py
@@ -124,6 +124,22 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == 200, response.json()
assert "results" in response.json()
+ def test_generic_query_endpoint_rejects_unknown_formula_alias_with_400(self) -> None:
+ # The facade reports a bad formula as ValueError; without the runner's
+ # translation to an exposed error, /query would surface it as a 500.
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/query/",
+ {
+ "query": {
+ "kind": "MetricsQuery",
+ "clauses": [{"name": "a", "metricName": "queue_depth", "aggregation": "sum"}],
+ "formula": "a / b",
+ }
+ },
+ )
+
+ assert response.status_code == 400, response.json()
+
def test_insight_saves_with_metrics_query(self) -> None:
response = self.client.post(
f"/api/projects/{self.team.pk}/insights/",
diff --git a/products/metrics/frontend/components/MetricNameFilter.tsx b/products/metrics/frontend/components/MetricNameFilter.tsx
index 063c2caf837f..37a2e6aabda2 100644
--- a/products/metrics/frontend/components/MetricNameFilter.tsx
+++ b/products/metrics/frontend/components/MetricNameFilter.tsx
@@ -96,8 +96,8 @@ function MetricNameFilterInner({
const onPick = useCallback(
(name: string) => {
- // Single-select: replace on pick. Multi-mode can be added later when
- // metrics-alerts arrives, mirroring ServiceFilter's selectionMode prop.
+ // Single-select: replace on pick. Comparing several metrics is done with
+ // clause rows (MetricsClauseRow), each holding its own picker.
onChange(value === name ? '' : name)
},
[value, onChange]
diff --git a/products/metrics/frontend/components/MetricsClauseFilterBar.tsx b/products/metrics/frontend/components/MetricsClauseFilterBar.tsx
new file mode 100644
index 000000000000..e557d1598edc
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsClauseFilterBar.tsx
@@ -0,0 +1,57 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'
+import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'
+import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+
+import { UniversalFiltersGroupValue } from '~/types'
+
+import { METRIC_FILTER_OPERATOR_ALLOWLIST } from './metricsViewerLogic'
+
+/** Filter chips + "Add filter" button for one clause row, mirroring the logs viewer's
+ * applied-filters row: picking an attribute opens the chip for value selection, with
+ * suggestions fed by the metrics attribute endpoints. Must render inside the row's
+ * `UniversalFilters` provider. */
+export function MetricsClauseFilterBar({ disabledReason }: { disabledReason: string | null }): JSX.Element {
+ const { filterGroup } = useValues(universalFiltersLogic)
+ const { replaceGroupValue, removeGroupValue } = useActions(universalFiltersLogic)
+ const [allowInitiallyOpen, setAllowInitiallyOpen] = useState<boolean>(false)
+
+ useOnMountEffect(() => setAllowInitiallyOpen(true))
+
+ return (
+ <div className="flex flex-wrap items-center gap-1">
+ {filterGroup.values.map((filterOrGroup: UniversalFiltersGroupValue, index: number) =>
+ // This UI only ever adds leaf filters, so nested groups can't occur here.
+ isUniversalGroupFilterLike(filterOrGroup) ? null : (
+ <span
+ key={index}
+ title={disabledReason ?? undefined}
+ className={disabledReason ? 'pointer-events-none opacity-50' : undefined}
+ >
+ <UniversalFilters.Value
+ index={index}
+ filter={filterOrGroup}
+ onRemove={disabledReason ? undefined : () => removeGroupValue(index)}
+ onChange={(value) => {
+ if (!disabledReason) {
+ replaceGroupValue(index, value)
+ }
+ }}
+ initiallyOpen={allowInitiallyOpen && !disabledReason}
+ operatorAllowlist={METRIC_FILTER_OPERATOR_ALLOWLIST}
+ />
+ </span>
+ )
+ )}
+ <UniversalFilters.AddFilterButton
+ size="small"
+ type="secondary"
+ title="Filter"
+ disabledReason={disabledReason}
+ />
+ </div>
+ )
+}
diff --git a/products/metrics/frontend/components/MetricsClauseRow.tsx b/products/metrics/frontend/components/MetricsClauseRow.tsx
new file mode 100644
index 000000000000..3073dc807aee
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsClauseRow.tsx
@@ -0,0 +1,174 @@
+import { useActions, useValues } from 'kea'
+
+import { IconEllipsis } from '@posthog/icons'
+import { LemonButton, LemonMenu, LemonSelect, Tooltip } from '@posthog/lemon-ui'
+
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'
+
+import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
+
+import { MetricNameFilter } from './MetricNameFilter'
+import { MetricsClauseFilterBar } from './MetricsClauseFilterBar'
+import { MetricsGroupByButton } from './MetricsGroupByButton'
+import {
+ MAX_CLAUSES,
+ MetricAggregation,
+ MetricsViewerClause,
+ RECOMMENDED_AGGREGATION_BY_TYPE,
+ metricsViewerLogic,
+} from './metricsViewerLogic'
+
+const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [
+ { value: 'sum', label: 'Sum' },
+ { value: 'avg', label: 'Average' },
+ { value: 'count', label: 'Series count' },
+ { value: 'min', label: 'Min' },
+ { value: 'max', label: 'Max' },
+ { value: 'p95', label: 'p95' },
+ { value: 'rate', label: 'Rate (/s)' },
+ { value: 'increase', label: 'Increase' },
+]
+
+/** One query line of the viewer: alias, metric picker, aggregation, filters, and group-by.
+ * Editing any control focuses the row — the samples panel, anomaly badge, and picker
+ * scoping follow the focused (active) clause. */
+export function MetricsClauseRow({
+ clause,
+ index,
+ isActive,
+ showAlias,
+ disabledReason,
+}: {
+ clause: MetricsViewerClause
+ index: number
+ isActive: boolean
+ /** Aliases only mean something once there is more than one series. */
+ showAlias: boolean
+ disabledReason: string | null
+}): JSX.Element {
+ const { viewerClauses, attributeEndpointFilters } = useValues(metricsViewerLogic)
+ const {
+ setActiveClauseIndex,
+ setMetricName,
+ setAggregation,
+ setFilterGroup,
+ setGroupByKeys,
+ duplicateClause,
+ removeClause,
+ } = useActions(metricsViewerLogic)
+
+ const select = (): void => {
+ if (!isActive) {
+ setActiveClauseIndex(index)
+ }
+ }
+
+ // Every control edit both focuses this row and applies its own change.
+ const withSelect =
+ <T,>(setter: (value: T) => void) =>
+ (value: T): void => {
+ select()
+ setter(value)
+ }
+
+ const recommendedAggregation = clause.selectedMetricType
+ ? RECOMMENDED_AGGREGATION_BY_TYPE[clause.selectedMetricType]
+ : undefined
+
+ return (
+ <div className="flex flex-wrap items-start gap-2" data-attr="metrics-clause-row">
+ {showAlias && (
+ <Tooltip
+ title={
+ isActive
+ ? 'Samples and related links follow this series'
+ : 'Click to focus this series. Samples and related links follow it.'
+ }
+ >
+ <LemonButton
+ size="small"
+ type={isActive ? 'primary' : 'secondary'}
+ onClick={select}
+ className="font-mono"
+ data-attr="metrics-clause-alias"
+ >
+ {clause.name}
+ </LemonButton>
+ </Tooltip>
+ )}
+ <div className="flex flex-col gap-1">
+ <MetricNameFilter
+ value={clause.metricName}
+ onChange={withSelect(setMetricName)}
+ disabled={!!disabledReason}
+ disabledReason={disabledReason}
+ />
+ {clause.selectedMetricType &&
+ recommendedAggregation &&
+ clause.aggregation !== recommendedAggregation && (
+ <span className="text-xs text-secondary">
+ {clause.selectedMetricType}: {recommendedAggregation} recommended
+ </span>
+ )}
+ </div>
+ <LemonSelect
+ size="small"
+ value={clause.aggregation}
+ options={AGGREGATION_OPTIONS}
+ onChange={withSelect(setAggregation)}
+ data-attr="metrics-viewer-aggregation"
+ disabledReason={disabledReason}
+ />
+ <UniversalFilters
+ // Keyed by the stable alias — an index key would rebind another row's
+ // filter logic when a row above it is removed.
+ rootKey={`metrics-viewer-filters-${clause.name}`}
+ group={clause.filterGroup.values[0] as UniversalFiltersGroup}
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.MetricAttributes]}
+ endpointFilters={attributeEndpointFilters}
+ onChange={(group) => {
+ if (!disabledReason) {
+ withSelect(setFilterGroup)({ type: FilterLogicalOperator.And, values: [group] })
+ }
+ }}
+ >
+ <MetricsClauseFilterBar disabledReason={disabledReason} />
+ </UniversalFilters>
+ <MetricsGroupByButton
+ groupByKeys={clause.groupByKeys}
+ onChange={withSelect(setGroupByKeys)}
+ disabledReason={disabledReason}
+ />
+ <LemonMenu
+ items={[
+ {
+ label: 'Duplicate',
+ onClick: () => duplicateClause(index),
+ disabledReason:
+ viewerClauses.length >= MAX_CLAUSES
+ ? `A query can have at most ${MAX_CLAUSES} series`
+ : undefined,
+ },
+ ...(viewerClauses.length > 1
+ ? [
+ {
+ label: 'Remove',
+ status: 'danger' as const,
+ onClick: () => removeClause(index),
+ },
+ ]
+ : []),
+ ]}
+ >
+ <LemonButton
+ size="small"
+ icon={<IconEllipsis />}
+ tooltip="Series options"
+ disabledReason={disabledReason}
+ data-attr="metrics-clause-row-menu"
+ />
+ </LemonMenu>
+ </div>
+ )
+}
diff --git a/products/metrics/frontend/components/MetricsGroupByButton.tsx b/products/metrics/frontend/components/MetricsGroupByButton.tsx
new file mode 100644
index 000000000000..0dfb01549cbd
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsGroupByButton.tsx
@@ -0,0 +1,76 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconChevronDown } from '@posthog/icons'
+import { LemonButton, LemonDropdown, LemonInputSelect } from '@posthog/lemon-ui'
+
+import { metricsViewerLogic } from './metricsViewerLogic'
+
+/** Group by is a button that opens the attribute multiselect, so the filter bar stays the
+ * primary control (mirrors how logs and traces keep grouping as a button, not the main bar). */
+export function MetricsGroupByButton({
+ groupByKeys,
+ onChange,
+ disabledReason,
+}: {
+ groupByKeys: string[]
+ onChange: (groupByKeys: string[]) => void
+ disabledReason: string | null
+}): JSX.Element {
+ const { attributeKeyOptions, attributeKeyOptionsLoading } = useValues(metricsViewerLogic)
+ const { setGroupBySearch, loadAttributeKeyOptions } = useActions(metricsViewerLogic)
+ const [open, setOpen] = useState<boolean>(false)
+
+ const label =
+ groupByKeys.length === 0
+ ? 'Group by'
+ : groupByKeys.length === 1
+ ? `Group by: ${groupByKeys[0]}`
+ : `Group by: ${groupByKeys.length} attributes`
+
+ return (
+ <LemonDropdown
+ visible={open}
+ closeOnClickInside={false}
+ onClickOutside={() => setOpen(false)}
+ overlay={
+ <div className="p-1 w-[18rem]">
+ <LemonInputSelect
+ mode="multiple"
+ size="small"
+ allowCustomValues
+ value={groupByKeys}
+ onChange={onChange}
+ options={attributeKeyOptions}
+ loading={attributeKeyOptionsLoading}
+ onInputChange={setGroupBySearch}
+ onFocus={() => loadAttributeKeyOptions({})}
+ placeholder="Group by attribute…"
+ data-attr="metrics-viewer-group-by"
+ disabledReason={disabledReason}
+ autoFocus
+ />
+ </div>
+ }
+ >
+ <LemonButton
+ size="small"
+ type="secondary"
+ active={open || groupByKeys.length > 0}
+ sideIcon={<IconChevronDown />}
+ onClick={() => {
+ setOpen((wasOpen) => !wasOpen)
+ loadAttributeKeyOptions({})
+ }}
+ disabledReason={disabledReason ?? undefined}
+ data-attr="metrics-viewer-group-by-button"
+ // Attribute keys can be long, so cap the trigger rather than let it push the row wide
+ truncate
+ className="max-w-[16rem]"
+ tooltip={groupByKeys.length > 0 ? groupByKeys.join(', ') : undefined}
+ >
+ {label}
+ </LemonButton>
+ </LemonDropdown>
+ )
+}
diff --git a/products/metrics/frontend/components/MetricsSamplesPanel.tsx b/products/metrics/frontend/components/MetricsSamplesPanel.tsx
index e826fe492321..b8cd65f4118f 100644
--- a/products/metrics/frontend/components/MetricsSamplesPanel.tsx
+++ b/products/metrics/frontend/components/MetricsSamplesPanel.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
-import { LemonTable, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonSegmentedButton, LemonTable, LemonTabs, Link, Tooltip } from '@posthog/lemon-ui'
import { getColorVar } from 'lib/colors'
import { TZLabel } from 'lib/components/TZLabel'
@@ -150,6 +150,8 @@ function AggregatesTab(): JSX.Element {
export function MetricsSamplesPanel(): JSX.Element {
const { activeTab } = useValues(metricsSamplesLogic)
const { setActiveTab } = useActions(metricsSamplesLogic)
+ const { viewerClauses, activeClauseIndex } = useValues(metricsViewerLogic)
+ const { setActiveClauseIndex } = useActions(metricsViewerLogic)
const metricsViewerDisabledReason = getAccessControlDisabledReason(
AccessControlResourceType.Metrics,
AccessControlLevel.Viewer
@@ -157,6 +159,28 @@ export function MetricsSamplesPanel(): JSX.Element {
return (
<div className="border rounded p-2 overflow-y-auto">
+ {/* Samples and the anomaly badge describe one series at a time; with several
+ clauses this picks which one they follow. Aggregates always cover all series. */}
+ {viewerClauses.length > 1 && (
+ <div className="flex flex-wrap items-center gap-2 pb-1">
+ <span className="text-xs text-secondary">Samples follow series</span>
+ <LemonSegmentedButton
+ size="xsmall"
+ value={activeClauseIndex}
+ onChange={(index) => {
+ if (!metricsViewerDisabledReason) {
+ setActiveClauseIndex(index)
+ }
+ }}
+ options={viewerClauses.map((clause, index) => ({
+ value: index,
+ label: clause.name,
+ tooltip: clause.metricName.trim() || 'No metric picked',
+ }))}
+ data-attr="metrics-samples-panel-series-picker"
+ />
+ </div>
+ )}
<LemonTabs<MetricsPanelTab>
size="small"
activeKey={activeTab}
diff --git a/products/metrics/frontend/components/MetricsSeriesChart.tsx b/products/metrics/frontend/components/MetricsSeriesChart.tsx
index 3ca517ca3cd1..452e605a86f0 100644
--- a/products/metrics/frontend/components/MetricsSeriesChart.tsx
+++ b/products/metrics/frontend/components/MetricsSeriesChart.tsx
@@ -19,7 +19,7 @@ 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'
+import { formatSeriesNames, type MetricsChartSeries, seriesColor } from './metricsSeries'
const AREA_FILL_OPACITY = 0.2
@@ -44,18 +44,20 @@ export function MetricsSeriesChart({
const isBar = display?.type === 'bar'
const isArea = display?.type === 'area'
- const chartSeries = useMemo<Series[]>(
- () =>
- series.map((s, index) => ({
- key: `${index}`,
- label: formatSeriesName({ labels: s.labels, metric_name: s.metricName ?? undefined }, fallbackName),
- // 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, isArea]
- )
+ const chartSeries = useMemo<Series[]>(() => {
+ const names = formatSeriesNames(
+ series.map((s) => ({ labels: s.labels, metric_name: s.metricName ?? undefined, clause: s.clause })),
+ fallbackName
+ )
+ return series.map((s, index) => ({
+ key: `${index}`,
+ label: names[index],
+ // 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, isArea])
const labels = useMemo(() => (series[0]?.points ?? []).map((p) => p.time), [series])
const sharedConfig = useChartConfig<TimeSeriesLineChartConfig>(
diff --git a/products/metrics/frontend/components/MetricsViewer.test.tsx b/products/metrics/frontend/components/MetricsViewer.test.tsx
index 8ef47d855b53..4df75f87b4b9 100644
--- a/products/metrics/frontend/components/MetricsViewer.test.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.test.tsx
@@ -69,6 +69,22 @@ describe('MetricsViewer', () => {
logic?.unmount()
})
+ // The formula input only means something once a second series can feed it; showing it
+ // is what makes the multi-series feature discoverable at all.
+ it('reveals a second clause row and the formula input when a series is added', async () => {
+ render(
+ <Provider>
+ <MetricsViewer />
+ </Provider>
+ )
+ expect(screen.queryByPlaceholderText('Formula, e.g. (a - b) / a')).toBeNull()
+
+ fireEvent.click(screen.getByText('Add series'))
+
+ expect(await screen.findByPlaceholderText('Formula, e.g. (a - b) / a')).toBeInTheDocument()
+ expect(logic.values.viewerClauses).toHaveLength(2)
+ })
+
// "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.tsx
index b81864dc2236..b5c5c6abb4d3 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -2,49 +2,36 @@ import { useActions, useMountedLogic, useValues } from 'kea'
import { router } from 'kea-router'
import { useEffect, useMemo, useState } from 'react'
-import { IconChevronDown } from '@posthog/icons'
+import { IconPlusSmall } from '@posthog/icons'
import {
- LemonButton,
LemonBanner,
- LemonDropdown,
- LemonInputSelect,
+ LemonButton,
+ LemonInput,
LemonSelect,
LemonSwitch,
SpinnerOverlay,
+ Tooltip,
} from '@posthog/lemon-ui'
import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboardModal'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'
-import { universalFiltersLogic } from 'lib/components/UniversalFilters/universalFiltersLogic'
-import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { dayjs } from 'lib/dayjs'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils/datetime'
import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'
import { urls } from 'scenes/urls'
import type { MetricsDisplayType } from '~/queries/schema/schema-general'
-import {
- AccessControlLevel,
- AccessControlResourceType,
- DateMappingOption,
- FilterLogicalOperator,
- UniversalFiltersGroup,
- UniversalFiltersGroupValue,
-} from '~/types'
+import { AccessControlLevel, AccessControlResourceType, DateMappingOption } from '~/types'
import { traceUrl } from 'products/tracing/frontend/traceLinks'
import { getMetricsInsightEditorDisabledReason } from '../metricsAccess'
-import { MetricNameFilter } from './MetricNameFilter'
-import { metricNamePickerLogic } from './metricNamePickerLogic'
import { MetricsAnomalyPanel } from './MetricsAnomalyPanel'
import { MetricsChartSettings } from './MetricsChartSettings'
+import { MetricsClauseRow } from './MetricsClauseRow'
import { type MetricsExemplar } from './MetricsExemplarMarkers'
import { MetricsLogsSourceTag } from './MetricsLogsSourceTag'
import { MetricsRelatedMenu } from './MetricsRelatedMenu'
@@ -54,13 +41,7 @@ import { MetricsSeriesChart } from './MetricsSeriesChart'
import { metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'
import { MetricsStarterDashboardModal } from './MetricsStarterDashboardModal'
import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'
-import {
- LIVE_REFRESH_MS,
- METRIC_FILTER_OPERATOR_ALLOWLIST,
- MetricAggregation,
- metricsViewerLogic,
- RECOMMENDED_AGGREGATION_BY_TYPE,
-} from './metricsViewerLogic'
+import { LIVE_REFRESH_MS, MAX_CLAUSES, metricsViewerLogic, sanitizeFormulaInput } 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 }[] = [
@@ -69,17 +50,6 @@ const DISPLAY_TYPE_OPTIONS: { value: MetricsDisplayType; label: string }[] = [
{ value: 'bar', label: 'Bar' },
]
-const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [
- { value: 'sum', label: 'Sum' },
- { value: 'avg', label: 'Average' },
- { value: 'count', label: 'Series count' },
- { value: 'min', label: 'Min' },
- { value: 'max', label: 'Max' },
- { value: 'p95', label: 'p95' },
- { value: 'rate', label: 'Rate (/s)' },
- { value: 'increase', label: 'Increase' },
-]
-
// Mirrors the curated set used by `LogsViewer/Filters/DateRangeFilter`.
const DATE_OPTIONS: DateMappingOption[] = [
{ key: CUSTOM_OPTION_KEY, values: [] },
@@ -117,21 +87,19 @@ const DATE_OPTIONS: DateMappingOption[] = [
export const MetricsViewer = (): JSX.Element => {
const logic = metricsViewerLogic()
- // Keep the picker logic mounted alongside the viewer so the chosen metric's
- // metric_type stays available for the aggregation hint after the dropdown closes.
- const pickerLogic = useMountedLogic(metricNamePickerLogic())
// The side panel's logic listens to this viewer's filter changes; mounting it
// here keeps samples in sync even while the panel itself is off-screen.
useMountedLogic(metricsSamplesLogic())
const { openModal: openStarterDashboardModal } = useActions(metricsStarterDashboardLogic)
const {
+ viewerClauses,
+ activeClauseIndex,
+ formula,
+ queryFingerprint,
+ anomalyFingerprint,
metricName,
- aggregation,
dateFrom,
dateTo,
- groupByKeys,
- filterGroup,
- attributeEndpointFilters,
chartSeries,
anomalyBadge,
liveRefresh,
@@ -146,12 +114,10 @@ export const MetricsViewer = (): JSX.Element => {
metricsDisplay,
} = useValues(logic)
const {
- setMetricName,
- setAggregation,
setDateFrom,
setDateTo,
- setFilterGroup,
setLiveRefresh,
+ addClause,
fetchQueryResults,
fetchAnomaly,
clearAnomaly,
@@ -160,7 +126,6 @@ export const MetricsViewer = (): JSX.Element => {
closeAddToDashboardModal,
setDisplayType,
} = useActions(logic)
- const { items: pickerItems } = useValues(pickerLogic)
const { traceExemplars, errorSpikes, showErrorSpikes } = useValues(metricsSamplesLogic)
const { toggleShowErrorSpikes } = useActions(metricsSamplesLogic)
// Staff-only PoC gate, layered on top of the wider metrics alpha flag.
@@ -223,59 +188,60 @@ export const MetricsViewer = (): JSX.Element => {
errorTrackingDisabledReason,
])
- // Refetch the chart whenever any filter changes — the loader breakpoint debounces input.
+ // Refetch the chart whenever the effective query changes — the fingerprints are
+ // strings, so edits that don't change the request (a blank just-added row, a
+ // group-by tweak the anomaly body doesn't carry) don't refire the effects.
+ // The loader breakpoint debounces input.
useEffect(() => {
fetchQueryResults({})
- }, [metricName, aggregation, dateFrom, dateTo, groupByKeys, filterGroup]) // eslint-disable-line react-hooks/exhaustive-deps
+ }, [queryFingerprint, dateFrom, dateTo]) // eslint-disable-line react-hooks/exhaustive-deps
// Characterize the recent window against the rest, so the chart carries a "vs baseline"
- // badge without the user having to eyeball the shape.
+ // badge without the user having to eyeball the shape. The loader suppresses the badge
+ // for multi-series and formula queries, where no single input series describes the chart.
useEffect(() => {
if (hasMetricName) {
fetchAnomaly({})
} else {
clearAnomaly()
}
- }, [metricName, aggregation, dateFrom, dateTo, hasMetricName, filterGroup]) // eslint-disable-line react-hooks/exhaustive-deps
+ }, [anomalyFingerprint, dateFrom, dateTo, hasMetricName]) // eslint-disable-line react-hooks/exhaustive-deps
- const selectedMetricType = useMemo(
- () => pickerItems.find((item) => item.name === metricName)?.metric_type,
- [pickerItems, metricName]
- )
- const recommendedAggregation = selectedMetricType ? RECOMMENDED_AGGREGATION_BY_TYPE[selectedMetricType] : undefined
+ const showFormulaInput = viewerClauses.length > 1 || formula !== ''
return (
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-2">
- {/* The filter bar is the primary control, mirroring logs and traces. */}
- <div className="flex flex-wrap items-center gap-2 justify-between">
- <div className="flex flex-1 flex-wrap items-center gap-2 min-w-[16rem]">
- <div className="flex flex-col gap-1">
- <MetricNameFilter
- value={metricName}
- onChange={setMetricName}
- disabled={!!metricsViewerDisabledReason}
+ <div className="flex flex-wrap items-start gap-2 justify-between">
+ <div className="flex flex-col gap-2 flex-1 min-w-[16rem]">
+ {viewerClauses.map((clause, index) => (
+ <MetricsClauseRow
+ key={clause.name}
+ clause={clause}
+ index={index}
+ isActive={index === activeClauseIndex}
+ showAlias={viewerClauses.length > 1}
disabledReason={metricsViewerDisabledReason}
/>
- {selectedMetricType && recommendedAggregation && aggregation !== recommendedAggregation && (
- <span className="text-xs text-secondary">
- {selectedMetricType} — {recommendedAggregation} recommended
- </span>
- )}
- </div>
- <UniversalFilters
- rootKey="metrics-viewer-filters"
- group={filterGroup.values[0] as UniversalFiltersGroup}
- taxonomicGroupTypes={[TaxonomicFilterGroupType.MetricAttributes]}
- endpointFilters={attributeEndpointFilters}
- onChange={(group) => {
- if (!metricsViewerDisabledReason) {
- setFilterGroup({ type: FilterLogicalOperator.And, values: [group] })
+ ))}
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPlusSmall />}
+ onClick={() => addClause()}
+ disabledReason={
+ metricsViewerDisabledReason ??
+ (viewerClauses.length >= MAX_CLAUSES
+ ? `A query can have at most ${MAX_CLAUSES} series`
+ : undefined)
}
- }}
- >
- <MetricsViewerFilterBar disabledReason={metricsViewerDisabledReason} />
- </UniversalFilters>
+ data-attr="metrics-viewer-add-series"
+ >
+ Add series
+ </LemonButton>
+ {showFormulaInput && <MetricsFormulaInput disabledReason={metricsViewerDisabledReason} />}
+ </div>
</div>
<div className="flex flex-wrap items-center gap-2">
<DateFilter
@@ -317,18 +283,8 @@ export const MetricsViewer = (): JSX.Element => {
)}
</div>
</div>
- {/* Aggregation and grouping controls sit below the filter bar. */}
<div className="flex flex-wrap items-center gap-2 justify-between">
<div className="flex flex-wrap items-center gap-2">
- <LemonSelect
- size="small"
- value={aggregation}
- options={AGGREGATION_OPTIONS}
- onChange={(value) => setAggregation(value as MetricAggregation)}
- data-attr="metrics-viewer-aggregation"
- disabledReason={metricsViewerDisabledReason}
- />
- <MetricsGroupByButton disabledReason={metricsViewerDisabledReason} />
<LemonSelect
size="small"
value={displayType}
@@ -410,7 +366,7 @@ export const MetricsViewer = (): JSX.Element => {
) : hasResults ? (
<MetricsSeriesChart
series={chartSeries}
- fallbackName={metricName}
+ fallbackName={formula || metricName || 'metric'}
display={metricsDisplay}
exemplars={chartMarkers}
/>
@@ -435,107 +391,38 @@ export const MetricsViewer = (): JSX.Element => {
// How the recent slice of the window compares against the rest of it, sitting next to the
// controls that define the window rather than over the chart, where it would fight the legend.
-// Filter chips + "Add filter" button, mirroring the logs viewer's applied-filters row: picking an
-// attribute opens the chip for value selection, with suggestions fed by the metrics attribute endpoints.
-const MetricsViewerFilterBar = ({ disabledReason }: { disabledReason: string | null }): JSX.Element => {
- const { filterGroup } = useValues(universalFiltersLogic)
- const { replaceGroupValue, removeGroupValue } = useActions(universalFiltersLogic)
- const [allowInitiallyOpen, setAllowInitiallyOpen] = useState<boolean>(false)
+// Committed on blur/Enter (mirroring TrendsFormula) so a half-typed formula doesn't fire
+// a query per keystroke. Input is lowercased — clause aliases are lowercase and the
+// backend parser is case-sensitive.
+const MetricsFormulaInput = ({ disabledReason }: { disabledReason: string | null }): JSX.Element => {
+ const { formula } = useValues(metricsViewerLogic)
+ const { setFormula } = useActions(metricsViewerLogic)
+ const [draft, setDraft] = useState(formula)
- useOnMountEffect(() => setAllowInitiallyOpen(true))
+ // An external change (URL restore, clause reset) replaces the local draft.
+ useEffect(() => {
+ setDraft(formula)
+ }, [formula])
+
+ const commit = (): void => {
+ if (draft !== formula) {
+ setFormula(draft)
+ }
+ }
return (
- <div className="flex flex-wrap items-center gap-1">
- {filterGroup.values.map((filterOrGroup: UniversalFiltersGroupValue, index: number) =>
- // This UI only ever adds leaf filters, so nested groups can't occur here.
- isUniversalGroupFilterLike(filterOrGroup) ? null : (
- <span
- key={index}
- title={disabledReason ?? undefined}
- className={disabledReason ? 'pointer-events-none opacity-50' : undefined}
- >
- <UniversalFilters.Value
- index={index}
- filter={filterOrGroup}
- onRemove={disabledReason ? undefined : () => removeGroupValue(index)}
- onChange={(value) => {
- if (!disabledReason) {
- replaceGroupValue(index, value)
- }
- }}
- initiallyOpen={allowInitiallyOpen && !disabledReason}
- operatorAllowlist={METRIC_FILTER_OPERATOR_ALLOWLIST}
- />
- </span>
- )
- )}
- <UniversalFilters.AddFilterButton
+ <Tooltip title="Arithmetic over the series letters, with + - * / and parentheses. Only the formula result is charted.">
+ <LemonInput
size="small"
- type="secondary"
- title="Filter"
+ className="min-w-48"
+ value={draft}
+ onChange={(value) => setDraft(sanitizeFormulaInput(value))}
+ onBlur={commit}
+ onPressEnter={commit}
+ placeholder="Formula, e.g. (a - b) / a"
+ data-attr="metrics-viewer-formula"
disabledReason={disabledReason}
/>
- </div>
- )
-}
-
-// Group by is a button that opens the attribute multiselect, so the filter bar stays the
-// primary control (mirrors how logs and traces keep grouping as a button, not the main bar).
-const MetricsGroupByButton = ({ disabledReason }: { disabledReason: string | null }): JSX.Element => {
- const { groupByKeys, attributeKeyOptions, attributeKeyOptionsLoading } = useValues(metricsViewerLogic)
- const { setGroupByKeys, setGroupBySearch, loadAttributeKeyOptions } = useActions(metricsViewerLogic)
- const [open, setOpen] = useState<boolean>(false)
-
- const label =
- groupByKeys.length === 0
- ? 'Group by'
- : groupByKeys.length === 1
- ? `Group by: ${groupByKeys[0]}`
- : `Group by: ${groupByKeys.length} attributes`
-
- return (
- <LemonDropdown
- visible={open}
- closeOnClickInside={false}
- onClickOutside={() => setOpen(false)}
- overlay={
- <div className="p-1 w-[18rem]">
- <LemonInputSelect
- mode="multiple"
- size="small"
- allowCustomValues
- value={groupByKeys}
- onChange={setGroupByKeys}
- options={attributeKeyOptions}
- loading={attributeKeyOptionsLoading}
- onInputChange={setGroupBySearch}
- onFocus={() => loadAttributeKeyOptions({})}
- placeholder="Group by attribute…"
- data-attr="metrics-viewer-group-by"
- disabledReason={disabledReason}
- autoFocus
- />
- </div>
- }
- >
- <LemonButton
- size="small"
- type="secondary"
- active={open || groupByKeys.length > 0}
- sideIcon={<IconChevronDown />}
- onClick={() => {
- setOpen((wasOpen) => !wasOpen)
- loadAttributeKeyOptions({})
- }}
- disabledReason={disabledReason ?? undefined}
- data-attr="metrics-viewer-group-by-button"
- // Attribute keys can be long, so cap the trigger rather than let it push the row wide
- truncate
- className="max-w-[16rem]"
- tooltip={groupByKeys.length > 0 ? groupByKeys.join(', ') : undefined}
- >
- {label}
- </LemonButton>
- </LemonDropdown>
+ </Tooltip>
)
}
diff --git a/products/metrics/frontend/components/metricsSamplesLogic.tsx b/products/metrics/frontend/components/metricsSamplesLogic.tsx
index 4b425d810db9..f57ab360dcc3 100644
--- a/products/metrics/frontend/components/metricsSamplesLogic.tsx
+++ b/products/metrics/frontend/components/metricsSamplesLogic.tsx
@@ -15,7 +15,7 @@ import type {
} from 'products/metrics/frontend/generated/api.schemas'
import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'
-import { formatSeriesName, seriesColor } from './metricsSeries'
+import { formatSeriesNames, seriesColor } from './metricsSeries'
import { type MetricsViewerSeries, metricsViewerLogic, resolveDate } from './metricsViewerLogic'
// The side panel next to the chart: per-series aggregates, or the raw emissions
@@ -62,6 +62,12 @@ export interface metricsSamplesLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSamplesLogicActions {
+ addClause: () => {
+ value: true
+ } // metricsViewerLogic
+ duplicateClause: (index: number) => {
+ index: number
+ } // metricsViewerLogic
fetchQueryResultsSuccess: (
queryResults: import('products/metrics/frontend/generated/api.schemas')._MetricSeriesApi[],
payload?: any
@@ -69,6 +75,12 @@ export interface metricsSamplesLogicActions {
payload?: any
queryResults: import('products/metrics/frontend/generated/api.schemas')._MetricSeriesApi[]
} // metricsViewerLogic
+ removeClause: (index: number) => {
+ index: number
+ } // metricsViewerLogic
+ setActiveClauseIndex: (index: number) => {
+ index: number
+ } // metricsViewerLogic
setDateFrom: (dateFrom: string | null) => {
dateFrom: string | null
} // metricsViewerLogic
@@ -157,6 +169,10 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
'setDateTo',
'setFilterGroup',
'setSelectedMetricType',
+ 'setActiveClauseIndex',
+ 'addClause',
+ 'removeClause',
+ 'duplicateClause',
'fetchQueryResultsSuccess',
],
],
@@ -235,18 +251,20 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
// views always describe the same query (colors match the chart legend).
aggregateRows: [
(s) => [s.queryResults, s.metricName],
- (queryResults: MetricsViewerSeries[], metricName: string): MetricsAggregateRow[] =>
- queryResults.map((series, index) => {
+ (queryResults: MetricsViewerSeries[], metricName: string): MetricsAggregateRow[] => {
+ const names = formatSeriesNames(queryResults, metricName)
+ return queryResults.map((series, index) => {
// Null points are gaps (unrepresentable buckets) — skip them
// rather than counting them as zero.
const values = series.points.map((point) => point.value).filter((value) => value !== null)
return {
- name: formatSeriesName(series, metricName),
+ name: names[index],
color: seriesColor(index),
latest: values.length ? values[values.length - 1] : 0,
total: values.reduce((sum, value) => sum + value, 0),
}
- }),
+ })
+ },
],
// Exemplar dots for the chart: only emissions that carry trace context.
traceExemplars: [
@@ -294,6 +312,25 @@ export const metricsSamplesLogic = kea<metricsSamplesLogicType>([
// The viewer pins the type in its own setMetricName listener, so without
// this a metric switch can load samples pinned to the previous type.
setSelectedMetricType: reloadWhenShown,
+ // Samples (and the exemplar dots derived from them) describe the active
+ // clause, and every clause-navigation action can move it — including the
+ // ones that leave the chart query unchanged (a blank row added or removed),
+ // so the chart-refetch fallback doesn't cover them. Refresh even while the
+ // tab is hidden; the exemplar overlay renders from these samples.
+ // (A late type backfill needs no trigger here: it always changes the chart
+ // query, and fetchQueryResultsSuccess reloads samples after that refetch.)
+ setActiveClauseIndex: () => {
+ actions.loadSamples({})
+ },
+ addClause: () => {
+ actions.loadSamples({})
+ },
+ removeClause: () => {
+ actions.loadSamples({})
+ },
+ duplicateClause: () => {
+ actions.loadSamples({})
+ },
}
}),
])
diff --git a/products/metrics/frontend/components/metricsSeries.ts b/products/metrics/frontend/components/metricsSeries.ts
index 41037a141a20..bcb82f53b5b8 100644
--- a/products/metrics/frontend/components/metricsSeries.ts
+++ b/products/metrics/frontend/components/metricsSeries.ts
@@ -6,6 +6,8 @@ export interface MetricsChartSeries {
labels: Record<string, string>
points: { time: string; value: number | null }[]
metricName?: string | null
+ /** Alias of the query clause that produced this series (`formula` for a formula result). */
+ clause?: string | null
}
// PostHog defines data-color-1..15 in vars.scss; cycle through them so each series gets a distinct line.
@@ -13,15 +15,24 @@ const SERIES_COLOR_COUNT = 15
export const seriesColor = (index: number): string => `data-color-${(index % SERIES_COLOR_COUNT) + 1}`
+type NamableSeries = Pick<_MetricSeriesApi, 'labels' | 'metric_name'> & { clause?: string | null }
+
// Human-readable series name from its label map (e.g. "service.name=checkout, env=prod"),
// falling back to the metric name then a provided default for ungrouped/unlabelled series.
-export const formatSeriesName = (
- series: Pick<_MetricSeriesApi, 'labels' | 'metric_name'>,
- fallback: string
-): string => {
+const formatSeriesName = (series: NamableSeries, fallback: string, showClause: boolean): string => {
+ const prefix = showClause && series.clause ? `${series.clause} · ` : ''
const entries = Object.entries(series.labels ?? {})
if (entries.length > 0) {
- return entries.map(([key, value]) => `${key}=${value}`).join(', ')
+ return prefix + entries.map(([key, value]) => `${key}=${value}`).join(', ')
}
- return series.metric_name ?? fallback
+ return prefix + (series.metric_name ?? fallback)
+}
+
+/** Display names for a whole chart's series, index-aligned with the input. The clause
+ * alias prefixes each name (e.g. "a · env=prod") only when the list plots more than
+ * one clause — that is the case where two ungrouped series would otherwise collide,
+ * and deciding here keeps every consumer (legend, aggregates table) in agreement. */
+export const formatSeriesNames = (seriesList: NamableSeries[], fallback: string): string[] => {
+ const showClause = new Set(seriesList.map((s) => s.clause).filter(Boolean)).size > 1
+ return seriesList.map((series) => formatSeriesName(series, fallback, showClause))
}
diff --git a/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx
index 923ac2f04911..7b354d3478fa 100644
--- a/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx
+++ b/products/metrics/frontend/components/metricsStarterDashboardLogic.tsx
@@ -16,7 +16,7 @@ import { metricsAttributeValuesRetrieve, metricsValuesRetrieve } from 'products/
import type { _MetricNameApi } from 'products/metrics/frontend/generated/api.schemas'
import type { InsightModel } from '../../../../frontend/src/types'
-import { RECOMMENDED_AGGREGATION_BY_TYPE, toKnownMetricType } from './metricsViewerLogic'
+import { RECOMMENDED_AGGREGATION_BY_TYPE, nodeAggregationFields, toKnownMetricType } from './metricsViewerLogic'
// A metric name can appear under more than one OTel type, so option identity
// must include both. \0 can't occur in ingest strings, so the key is collision-free.
@@ -219,9 +219,7 @@ export const metricsStarterDashboardLogic = kea<metricsStarterDashboardLogicType
const clause: MetricsQueryClause = {
name: 'a',
metricName,
- // The REST viewer's 'p95' shorthand maps to the node's quantile aggregation.
- aggregation: recommended === 'p95' ? 'quantile' : recommended,
- ...(recommended === 'p95' ? { quantile: 0.95 } : {}),
+ ...nodeAggregationFields(recommended),
...(metricType ? { metricType } : {}),
...(serviceName
? { filters: [{ key: 'service.name', op: 'eq' as const, value: serviceName }] }
diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
index 24de2717a7ca..b16f6ec85d7a 100644
--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts
@@ -110,7 +110,11 @@ describe('metricsUsageTrackingLogic', () => {
() => metricsSamplesLogic.actions.setActiveTab('samples'),
{ tab: 'samples' },
],
- ['metrics add to dashboard clicked', () => metricsViewerLogic.actions.addToDashboard(), { aggregation: 'sum' }],
+ [
+ 'metrics add to dashboard clicked',
+ () => metricsViewerLogic.actions.addToDashboard(),
+ { aggregation: 'sum', clause_count: 1, has_formula: false },
+ ],
[
// Reports the aggregation persisted on the insight, not the viewer's
// current one — those diverge when the user changes the aggregation
@@ -124,7 +128,7 @@ describe('metricsUsageTrackingLogic', () => {
} as any,
{} as any
),
- { aggregation: 'p95' },
+ { aggregation: 'p95', clause_count: 1, has_formula: false },
],
])('%s fires with enum/count properties only', (event, dispatch, expectedProperties) => {
dispatch()
diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
index c668e9bfdc88..f8148640584a 100644
--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts
@@ -16,16 +16,18 @@ import { metricsSceneLogic } from '../metricsSceneLogic'
import type { MetricsSceneActiveTab } from '../metricsSceneLogic'
import { metricsSamplesLogic } from './metricsSamplesLogic'
import type { MetricsPanelTab } from './metricsSamplesLogic'
-import { metricsViewerLogic } from './metricsViewerLogic'
-import type { MetricAggregation } from './metricsViewerLogic'
+import { metricsViewerLogic, viewerAggregationFromNode } from './metricsViewerLogic'
+import type { MetricAggregation, MetricsViewerClause } from './metricsViewerLogic'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsUsageTrackingLogicValues {
isRestoringFromUrl: boolean // metricsSceneLogic
aggregation: MetricAggregation // metricsViewerLogic
+ formula: string // metricsViewerLogic
groupByKeys: string[] // metricsViewerLogic
hasMetricName: boolean // metricsViewerLogic
queryFilters: _MetricFilterApi[] // metricsViewerLogic
+ viewerClauses: MetricsViewerClause[] // metricsViewerLogic
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -43,6 +45,9 @@ export interface metricsUsageTrackingLogicActions {
sceneTabChanged: (activeTab: MetricsSceneActiveTab) => {
activeTab: MetricsSceneActiveTab
} // metricsSceneLogic
+ addClause: () => {
+ value: true
+ } // metricsViewerLogic
addToDashboard: () => {
value: true
} // metricsViewerLogic
@@ -77,6 +82,9 @@ export interface metricsUsageTrackingLogicActions {
setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
filterGroup: UniversalFiltersGroup
} // metricsViewerLogic
+ setFormula: (formula: string) => {
+ formula: string
+ } // metricsViewerLogic
setGroupByKeys: (groupByKeys: string[]) => {
groupByKeys: string[]
} // metricsViewerLogic
@@ -123,6 +131,8 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
'setLiveRefresh',
'setGroupByKeys',
'setFilterGroup',
+ 'addClause',
+ 'setFormula',
'addToDashboard',
'saveAsInsightSuccess',
'fetchQueryResults',
@@ -136,7 +146,7 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
],
values: [
metricsViewerLogic,
- ['hasMetricName', 'aggregation', 'groupByKeys', 'queryFilters'],
+ ['hasMetricName', 'aggregation', 'groupByKeys', 'queryFilters', 'viewerClauses', 'formula'],
metricsSceneLogic,
['isRestoringFromUrl'],
],
@@ -185,8 +195,25 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
// queryFilters counts only complete, backend-valid chips (reducers ran before us).
posthog.capture('metrics viewer attribute filter changed', { filter_count: values.queryFilters.length })
},
+ addClause: () => {
+ posthog.capture('metrics viewer series added', { clause_count: values.viewerClauses.length })
+ },
+ // Only shape signals — the formula references clause letters, but stay consistent
+ // with the "no customer content" rule and capture booleans/counts only.
+ setFormula: ({ formula }) => {
+ if (!values.isRestoringFromUrl) {
+ posthog.capture('metrics viewer formula changed', {
+ has_formula: formula.trim().length > 0,
+ formula_length: formula.trim().length,
+ })
+ }
+ },
addToDashboard: () => {
- posthog.capture('metrics add to dashboard clicked', { aggregation: values.aggregation })
+ posthog.capture('metrics add to dashboard clicked', {
+ aggregation: values.aggregation,
+ clause_count: values.viewerClauses.length,
+ has_formula: !!values.formula,
+ })
},
saveAsInsightSuccess: ({ savedInsight }) => {
if (!savedInsight) {
@@ -194,10 +221,11 @@ export const metricsUsageTrackingLogic = kea<metricsUsageTrackingLogicType>([
}
// Read the aggregation off the insight itself — the viewer's current
// value can already differ if it changed while the save was in flight.
- // The node's 'quantile' maps back to the viewer vocabulary's 'p95'.
- const nodeAggregation = (savedInsight.query as MetricsQuery | undefined)?.clauses?.[0]?.aggregation
+ const savedQuery = savedInsight.query as MetricsQuery | undefined
posthog.capture('metrics insight saved', {
- aggregation: nodeAggregation === 'quantile' ? 'p95' : (nodeAggregation ?? null),
+ aggregation: viewerAggregationFromNode(savedQuery?.clauses?.[0]?.aggregation),
+ clause_count: savedQuery?.clauses?.length ?? null,
+ has_formula: !!savedQuery?.formula,
})
},
fetchQueryResults: () => {
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
index 5c6ce645dfb8..87230b4e9011 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -18,6 +18,7 @@ import {
import {
metricsAttributesRetrieve,
+ metricsCharacterizeCreate,
metricsQueryCreate,
metricsValuesRetrieve,
} from 'products/metrics/frontend/generated/api'
@@ -30,6 +31,7 @@ jest.mock('products/metrics/frontend/generated/api', () => ({
metricsValuesRetrieve: jest.fn(),
metricsAttributesRetrieve: jest.fn(),
metricsQueryCreate: jest.fn(),
+ metricsCharacterizeCreate: jest.fn(),
}))
jest.mock('scenes/insights/utils/api', () => ({
@@ -78,6 +80,7 @@ describe('metricsViewerLogic', () => {
jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: PICKER_ITEMS })
jest.mocked(metricsQueryCreate).mockReset().mockResolvedValue({ results: [] })
jest.mocked(metricsAttributesRetrieve).mockReset()
+ jest.mocked(metricsCharacterizeCreate).mockReset()
jest.mocked(insightsApi.create).mockReset()
logic = metricsViewerLogic()
logic.mount()
@@ -146,6 +149,139 @@ describe('metricsViewerLogic', () => {
expect(logic.values.metricsQueryNode).toBeNull()
})
+ // 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.
+ it('maps multiple clauses and a formula into the MetricsQuery node', () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.addClause()
+ logic.actions.setMetricName('queue_depth')
+ logic.actions.setFormula('A / b!')
+
+ expect(logic.values.metricsQueryNode).toEqual({
+ kind: NodeKind.MetricsQuery,
+ clauses: [
+ { name: 'a', metricName: 'requests_total', aggregation: 'increase', metricType: 'sum' },
+ { name: 'b', metricName: 'queue_depth', aggregation: 'avg', metricType: 'gauge' },
+ ],
+ formula: 'a / b',
+ dateRange: { date_from: '-1h' },
+ })
+ })
+
+ // The samples panel, anomaly badge, and picker scoping all read the active clause
+ // through the single-clause selectors — pointing them at the wrong clause silently
+ // shows one series' samples under another series' chart line.
+ it('single-clause setters and selectors follow the active clause', () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.addClause()
+ expect(logic.values.activeClauseIndex).toBe(1)
+
+ logic.actions.setMetricName('queue_depth')
+ expect(logic.values.viewerClauses.map((clause) => clause.metricName)).toEqual(['requests_total', 'queue_depth'])
+
+ logic.actions.setActiveClauseIndex(0)
+ expect(logic.values.metricName).toBe('requests_total')
+ expect(logic.values.aggregation).toBe('increase')
+ })
+
+ // A formula referencing a removed clause's alias can only 400 — a routine remove
+ // must leave the remaining series charted, not an error banner.
+ it('clears the formula when a clause it references is removed', () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.addClause()
+ logic.actions.setMetricName('queue_depth')
+ logic.actions.setFormula('a / b')
+
+ logic.actions.removeClause(1)
+
+ expect(logic.values.formula).toBe('')
+ expect(logic.values.viewerClauses).toHaveLength(1)
+ })
+
+ // Custom aliases from links can contain underscores (the backend tokenizer allows
+ // them); stripping them would mangle a valid formula into an unknown alias.
+ it('keeps underscores in formulas', () => {
+ logic.actions.setFormula('err_total / req_total')
+ expect(logic.values.formula).toBe('err_total / req_total')
+ })
+
+ // A formula references clauses by alias, so a duplicate alias after remove/add would
+ // silently rebind the formula (or be rejected by the backend as non-unique).
+ it('keeps aliases unique when clauses are removed and re-added', () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.addClause() // b
+ logic.actions.addClause() // c
+ logic.actions.removeClause(1)
+ logic.actions.addClause() // reuses the freed letter
+ expect(logic.values.viewerClauses.map((clause) => clause.name)).toEqual(['a', 'c', 'b'])
+ })
+
+ it('skips clauses without a metric when fetching, so a blank row does not fail the query', async () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.addClause()
+
+ await expectLogic(logic, () => {
+ logic.actions.fetchQueryResults({})
+ }).toDispatchActions(['fetchQueryResultsSuccess'])
+
+ const requestBody = jest.mocked(metricsQueryCreate).mock.calls[0][1]
+ expect(requestBody.query.clauses).toEqual([
+ expect.objectContaining({ name: 'a', metricName: 'requests_total' }),
+ ])
+ expect(requestBody.query).not.toHaveProperty('formula')
+ })
+
+ // A "vs baseline" badge computed from one input clause would be attributed to the
+ // whole (multi-series or formula) chart — suppressing it is the honest behavior.
+ it('suppresses the anomaly characterization for multi-series queries', async () => {
+ logic.actions.setMetricName('requests_total')
+ logic.actions.addClause()
+ logic.actions.setMetricName('queue_depth')
+
+ await expectLogic(logic, () => {
+ logic.actions.fetchAnomaly({})
+ }).toDispatchActions(['fetchAnomalySuccess'])
+
+ expect(metricsCharacterizeCreate).not.toHaveBeenCalled()
+ expect(logic.values.anomalyReport).toBeNull()
+ })
+
+ // 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.
+ it('aborts a superseded characterize request when a newer one starts', async () => {
+ jest.mocked(metricsCharacterizeCreate).mockImplementation(() => new Promise(() => {}))
+ logic.actions.setMetricName('requests_total')
+
+ logic.actions.fetchAnomaly({})
+ await new Promise((resolve) => setTimeout(resolve, 310))
+ expect(metricsCharacterizeCreate).toHaveBeenCalledTimes(1)
+ const firstSignal = jest.mocked(metricsCharacterizeCreate).mock.calls[0][2]?.signal
+ expect(firstSignal?.aborted).toBe(false)
+
+ logic.actions.fetchAnomaly({})
+ await new Promise((resolve) => setTimeout(resolve, 310))
+ expect(firstSignal?.aborted).toBe(true)
+ })
+
+ it('names a formula insight after the formula and its inputs', async () => {
+ jest.mocked(insightsApi.create).mockImplementation(
+ async (insight: any) => ({ id: 1, short_id: 'abc123', ...insight }) as any
+ )
+ logic.actions.setMetricName('requests_total')
+ logic.actions.addClause()
+ logic.actions.setMetricName('queue_depth')
+ logic.actions.setFormula('a / b')
+
+ logic.actions.saveAsInsight()
+ await expectLogic(logic).toDispatchActions(['saveAsInsightSuccess'])
+
+ expect(insightsApi.create).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'a / b (requests_total, queue_depth)' })
+ )
+ })
+
// A type outside the API enum (or a metric missing from the picker list) must be
// omitted, not persisted — the backend rejects unknown metric types.
it('omits metricType from the node when the picked type is unknown', () => {
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index c88de81e43eb..7740b91ef2b8 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -15,6 +15,7 @@ import {
isUserInitiatedError,
} from 'lib/utils/kea-logic-builders'
import { objectsEqual } from 'lib/utils/objects'
+import { alphabet, truncate } from 'lib/utils/strings'
import { insightsApi } from 'scenes/insights/utils/api'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -25,7 +26,6 @@ import {
MetricsDisplayType,
MetricsQuery,
MetricsQueryClause,
- MetricsQueryFilter,
MetricsYAxisSettings,
NodeKind,
} from '~/queries/schema/schema-general'
@@ -39,8 +39,11 @@ import {
} from 'products/metrics/frontend/generated/api'
import { OtelMetricTypeEnumApi } from 'products/metrics/frontend/generated/api.schemas'
import type {
+ _MetricAnomalyBodyApi,
_MetricAnomalyReportApi,
+ _MetricClauseApi,
_MetricFilterApi,
+ _MetricQueryBodyApi,
_MetricSeriesApi,
MetricAnomalyDirectionEnumApi,
} from 'products/metrics/frontend/generated/api.schemas'
@@ -69,6 +72,75 @@ export { EMPTY_SERVICE_PATTERN, SERVICE_NAME_KEY }
export type MetricsViewerSeries = _MetricSeriesApi
+/** One query line of the viewer — the state behind one clause row. */
+export interface MetricsViewerClause {
+ /** Alias a formula refers to; unique within the query (a, b, c…). */
+ name: string
+ metricName: string
+ selectedMetricType: OtelMetricTypeEnumApi | null
+ aggregation: MetricAggregation
+ aggregationExplicitlySet: boolean
+ filterGroup: UniversalFiltersGroup
+ groupByKeys: string[]
+}
+
+export interface MetricsViewerQueryState {
+ clauses: MetricsViewerClause[]
+ /** Which clause the samples panel, anomaly badge, and picker scoping follow. */
+ activeClauseIndex: number
+ /** Arithmetic over clause aliases (e.g. "a / b"); empty string means off. */
+ formula: string
+}
+
+/** One clause's share of the picker's late type/aggregation backfill. */
+export interface MetricsViewerClauseBackfill {
+ index: number
+ metricType?: OtelMetricTypeEnumApi
+ aggregation?: MetricAggregation
+}
+
+// Request-body slices the viewer assembles; the window fields are added at fetch time.
+export type MetricsQueryRequestBody = Pick<_MetricQueryBodyApi, 'clauses' | 'formula'>
+export type MetricsAnomalyRequestBody = Pick<_MetricAnomalyBodyApi, 'metricName' | 'aggregation' | 'filters'>
+
+// Mirrors the backend's MAX_CLAUSES_PER_QUERY.
+export const MAX_CLAUSES = 10
+// More letters than MAX_CLAUSES, so the cap is the only thing that limits adding
+// a series — a shorter alias supply would make "Add series" silently no-op.
+const CLAUSE_ALIASES = alphabet.map((letter) => letter.toLowerCase())
+
+export const createViewerClause = (name: string): MetricsViewerClause => ({
+ name,
+ metricName: '',
+ selectedMetricType: null,
+ aggregation: DEFAULT_AGGREGATION,
+ aggregationExplicitlySet: false,
+ filterGroup: DEFAULT_UNIVERSAL_GROUP_FILTER,
+ groupByKeys: [],
+})
+
+const nextClauseAlias = (clauses: MetricsViewerClause[]): string | null => {
+ if (clauses.length >= MAX_CLAUSES) {
+ return null
+ }
+ const used = new Set(clauses.map((clause) => clause.name))
+ for (const letter of CLAUSE_ALIASES) {
+ if (!used.has(letter)) {
+ return letter
+ }
+ }
+ return null
+}
+
+// Clause aliases are lowercase and the backend formula parser is case-sensitive,
+// so input is lowercased rather than rejected. Underscores stay — the alias grammar
+// (and the backend tokenizer) allows them. The backend caps formulas at 512 chars.
+export const sanitizeFormulaInput = (value: string): string =>
+ value
+ .toLowerCase()
+ .replace(/[^a-z0-9_ +\-*/().]/g, '')
+ .slice(0, 512)
+
// Display shape for the "vs baseline" anomaly badge (null = no anomaly / flat metric).
export interface MetricsAnomalyBadge {
direction: MetricAnomalyDirectionEnumApi
@@ -153,6 +225,12 @@ const propertyFilterToMetricFilter = (filter: UniversalFilterValue): _MetricFilt
const flattenFilterValues = (group: UniversalFiltersGroup): UniversalFilterValue[] =>
group.values.flatMap((value) => (isUniversalGroupFilterLike(value) ? flattenFilterValues(value) : [value]))
+/** A clause's filter bar as backend matchers, skipping chips still being edited. */
+export const metricFiltersForGroup = (group: UniversalFiltersGroup): _MetricFilterApi[] =>
+ flattenFilterValues(group)
+ .map(propertyFilterToMetricFilter)
+ .filter((f): f is _MetricFilterApi => f !== null)
+
/** The services a chip pins the query to, or `[]` when it isn't a membership test. */
const serviceChipValues = (chip: UniversalFilterValue): string[] => {
const operator = 'operator' in chip ? chip.operator : undefined
@@ -182,14 +260,90 @@ export const toKnownMetricType = (metricType: string | undefined): OtelMetricTyp
return metricType && known.includes(metricType) ? (metricType as OtelMetricTypeEnumApi) : null
}
+/** The REST viewer's 'p95' shorthand maps to the schema node's quantile aggregation. */
+export const nodeAggregationFields = (
+ aggregation: MetricAggregation
+): Pick<MetricsQueryClause, 'aggregation' | 'quantile'> =>
+ aggregation === 'p95' ? { aggregation: 'quantile', quantile: 0.95 } : { 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)
+
+const clauseToApiClause = (clause: MetricsViewerClause): _MetricClauseApi => {
+ const filters = metricFiltersForGroup(clause.filterGroup)
+ return {
+ name: clause.name,
+ metricName: clause.metricName.trim(),
+ aggregation: clause.aggregation,
+ // Pins the OTel type so a name that exists as several types (e.g. a counter
+ // and a gauge) charts only the picked one instead of blending them.
+ ...(clause.selectedMetricType ? { metricType: clause.selectedMetricType } : {}),
+ ...(filters.length ? { filters } : {}),
+ ...(clause.groupByKeys.length ? { groupBy: clause.groupByKeys.map((key) => ({ key })) } : {}),
+ }
+}
+
+// Derived from the API clause so a new clause field cannot reach one payload and
+// miss the other — the two shapes differ only in the aggregation vocabulary.
+const clauseToNodeClause = (clause: MetricsViewerClause): MetricsQueryClause =>
+ ({
+ ...clauseToApiClause(clause),
+ ...nodeAggregationFields(clause.aggregation),
+ }) as MetricsQueryClause
+
+const insightNameForViewerQuery = (clauses: MetricsViewerClause[], formula: string): string => {
+ const names = clauses.map((clause) => clause.metricName.trim())
+ let name: string
+ if (formula) {
+ name = `${formula} (${names.join(', ')})`
+ } else if (clauses.length > 1) {
+ name = `${names.join(', ')} (${clauses.length} series)`
+ } else {
+ name = `${names[0]} (${clauses[0].aggregation})`
+ }
+ return truncate(name, 120)
+}
+
+const DEFAULT_QUERY_STATE: MetricsViewerQueryState = {
+ clauses: [createViewerClause('a')],
+ activeClauseIndex: 0,
+ formula: '',
+}
+
+const withClauseAt = (
+ state: MetricsViewerQueryState,
+ index: number,
+ update: (clause: MetricsViewerClause) => MetricsViewerClause
+): MetricsViewerQueryState =>
+ state.clauses[index]
+ ? { ...state, clauses: state.clauses.map((clause, i) => (i === index ? update(clause) : clause)) }
+ : state
+
+const withActiveClause = (
+ state: MetricsViewerQueryState,
+ update: (clause: MetricsViewerClause) => MetricsViewerClause
+): MetricsViewerQueryState => withClauseAt(state, state.activeClauseIndex, update)
+
+// Aborts a still-running fetch superseded by a new one. An AbortError-named DOMException
+// (not a bare string) is what api.ts and the global loader onFailure recognize as a
+// cancellation, so the superseded fetch is swallowed rather than logged/captured as an error.
+const abortPrevious = (controller: AbortController | null): void => {
+ controller?.abort(new DOMException(NEW_QUERY_STARTED_ERROR_MESSAGE, 'AbortError'))
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsViewerLogicValues {
items: MetricNameItem[] // metricNamePickerLogic
pickerServices: string[] // metricNamePickerLogic
currentTeamId: number | null // teamLogic
+ activeClause: MetricsViewerClause
+ activeClauseIndex: number
aggregation: MetricAggregation
- aggregationExplicitlySet: boolean
+ anomalyAbortController: AbortController | null
anomalyBadge: MetricsAnomalyBadge | null
+ anomalyFingerprint: string
+ anomalyQuery: MetricsAnomalyRequestBody | null
anomalyReport: _MetricAnomalyReportApi | null
anomalyReportLoading: boolean
anomalyTopMovers: MetricTopMoverRow[]
@@ -205,6 +359,7 @@ export interface metricsViewerLogicValues {
dateTo: string | null
displayType: MetricsDisplayType
filterGroup: UniversalFiltersGroup
+ formula: string
goalLines: GoalLine[]
groupByKeys: string[]
groupBySearch: string
@@ -216,17 +371,22 @@ export interface metricsViewerLogicValues {
metricName: string
metricsDisplay: MetricsDisplaySettings | undefined
metricsQueryNode: MetricsQuery | null
+ namedClauses: MetricsViewerClause[]
pendingAddToDashboard: boolean
queryAbortController: AbortController | null
queryError: string | null
queryFilters: _MetricFilterApi[]
+ queryFingerprint: string
queryLoading: boolean
+ queryPayload: MetricsQueryRequestBody | null
queryResults: MetricsViewerSeries[]
queryResultsLoading: boolean
+ queryState: MetricsViewerQueryState
savedInsight: QueryBasedInsightModel | null
savedInsightLoading: boolean
selectedMetricType: OtelMetricTypeEnumApi | null
selectedServices: string[]
+ viewerClauses: MetricsViewerClause[]
yAxisSettings: MetricsYAxisSettings
}
@@ -255,12 +415,21 @@ export interface metricsViewerLogicActions {
key: string
value: string
}
+ addClause: () => {
+ value: true
+ }
addGoalLine: () => {
value: true
}
addToDashboard: () => {
value: true
}
+ backfillClauses: (updates: MetricsViewerClauseBackfill[]) => {
+ updates: MetricsViewerClauseBackfill[]
+ }
+ cancelInProgressAnomaly: (controller: AbortController | null) => {
+ controller: AbortController | null
+ }
cancelInProgressQuery: (controller: AbortController | null) => {
controller: AbortController | null
}
@@ -282,6 +451,9 @@ export interface metricsViewerLogicActions {
closeAddToDashboardModal: () => {
value: true
}
+ duplicateClause: (index: number) => {
+ index: number
+ }
fetchAnomaly: (_: any) => any
fetchAnomalyFailure: (
error: string,
@@ -336,6 +508,9 @@ export interface metricsViewerLogicActions {
openAddToDashboardModal: () => {
value: true
}
+ removeClause: (index: number) => {
+ index: number
+ }
removeGoalLine: (index: number) => {
index: number
}
@@ -354,9 +529,22 @@ export interface metricsViewerLogicActions {
savedInsight: QueryBasedInsightModel<Node<Record<string, any>>> | null
payload?: any
}
+ setActiveClauseIndex: (index: number) => {
+ index: number
+ }
setAggregation: (aggregation: MetricAggregation) => {
aggregation: MetricAggregation
}
+ setAnomalyAbortController: (controller: AbortController | null) => {
+ controller: AbortController | null
+ }
+ setClauses: (
+ clauses: MetricsViewerClause[],
+ formula: string
+ ) => {
+ clauses: MetricsViewerClause[]
+ formula: string
+ }
setDateFrom: (dateFrom: string | null) => {
dateFrom: string | null
}
@@ -369,6 +557,9 @@ export interface metricsViewerLogicActions {
setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
filterGroup: UniversalFiltersGroup
}
+ setFormula: (formula: string) => {
+ formula: string
+ }
setGroupByKeys: (groupByKeys: string[]) => {
groupByKeys: string[]
}
@@ -414,24 +605,35 @@ export interface metricsViewerLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsViewerLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- hasMetricName: (metricName: string) => boolean
+ viewerClauses: (queryState: MetricsViewerQueryState) => MetricsViewerClause[]
+ activeClauseIndex: (queryState: MetricsViewerQueryState) => number
+ formula: (queryState: MetricsViewerQueryState) => string
+ activeClause: (viewerClauses: MetricsViewerClause[], activeClauseIndex: number) => MetricsViewerClause
+ metricName: (activeClause: MetricsViewerClause) => string
+ selectedMetricType: (activeClause: MetricsViewerClause) => OtelMetricTypeEnumApi | null
+ aggregation: (activeClause: MetricsViewerClause) => MetricAggregation
+ groupByKeys: (activeClause: MetricsViewerClause) => string[]
+ filterGroup: (activeClause: MetricsViewerClause) => UniversalFiltersGroup
+ namedClauses: (viewerClauses: MetricsViewerClause[]) => MetricsViewerClause[]
+ hasMetricName: (namedClauses: MetricsViewerClause[]) => boolean
+ queryPayload: (namedClauses: MetricsViewerClause[], formula: string) => MetricsQueryRequestBody | null
+ queryFingerprint: (queryPayload: MetricsQueryRequestBody | null) => string
+ anomalyQuery: (namedClauses: MetricsViewerClause[], formula: string) => MetricsAnomalyRequestBody | null
+ anomalyFingerprint: (anomalyQuery: MetricsAnomalyRequestBody | null) => string
metricsDisplay: (
displayType: MetricsDisplayType,
goalLines: GoalLine[],
yAxisSettings: MetricsYAxisSettings
) => MetricsDisplaySettings | undefined
metricsQueryNode: (
- metricName: string,
- aggregation: MetricAggregation,
- selectedMetricType: OtelMetricTypeEnumApi | null,
+ namedClauses: MetricsViewerClause[],
+ formula: string,
dateFrom: string | null,
dateTo: string | null,
- groupByKeys: string[],
- queryFilters: _MetricFilterApi[],
metricsDisplay: MetricsDisplaySettings | undefined
) => MetricsQuery | null
- queryFilters: (filterGroup: UniversalFiltersGroup) => _MetricFilterApi[]
- selectedServices: (filterGroup: UniversalFiltersGroup) => string[]
+ queryFilters: (activeClause: MetricsViewerClause) => _MetricFilterApi[]
+ selectedServices: (activeClause: MetricsViewerClause) => string[]
correlationServices: (selectedServices: string[], queryResults: _MetricSeriesApi[]) => string[]
attributeEndpointFilters: (dateFrom: string | null, dateTo: string | null) => Record<string, string>
chartSeries: (queryResults: _MetricSeriesApi[]) => MetricsChartSeries[]
@@ -455,18 +657,31 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
actions: [metricNamePickerLogic, ['loadItemsSuccess', 'setServices']],
})),
actions({
+ // The single-clause setters target the active clause, so everything that
+ // followed the viewer's one metric (URL sync, samples, usage tracking)
+ // keeps working unchanged with several clauses on screen.
setMetricName: (metricName: string) => ({ metricName }),
setSelectedMetricType: (metricType: OtelMetricTypeEnumApi | null) => ({ metricType }),
setAggregation: (aggregation: MetricAggregation) => ({ aggregation }),
// Auto-applied on metric switch — a separate action so usage tracking can
// tell it apart from the user picking an aggregation themselves.
setRecommendedAggregation: (aggregation: MetricAggregation) => ({ aggregation }),
+ setGroupByKeys: (groupByKeys: string[]) => ({ groupByKeys }),
+ setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),
+ addClause: true,
+ removeClause: (index: number) => ({ index }),
+ duplicateClause: (index: number) => ({ index }),
+ setActiveClauseIndex: (index: number) => ({ index }),
+ setFormula: (formula: string) => ({ formula }),
+ // Bulk replace, used by the scene's URL restore.
+ setClauses: (clauses: MetricsViewerClause[], formula: string) => ({ clauses, formula }),
+ // The picker's late type/aggregation backfill, applied to every clause in one
+ // pass so a 10-clause deep link costs one reducer run and one URL write.
+ backfillClauses: (updates: MetricsViewerClauseBackfill[]) => ({ updates }),
setDateFrom: (dateFrom: string | null) => ({ dateFrom }),
setDateTo: (dateTo: string | null) => ({ dateTo }),
setLiveRefresh: (liveRefresh: boolean) => ({ liveRefresh }),
- setGroupByKeys: (groupByKeys: string[]) => ({ groupByKeys }),
setGroupBySearch: (groupBySearch: string) => ({ groupBySearch }),
- setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),
// Narrows the chart to one label value, from the anomaly panel's ranked movers.
addAttributeFilter: (key: string, value: string) => ({ key, value }),
// Saves the current query as an insight (reusing the last save while the
@@ -479,6 +694,8 @@ 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 }),
+ setAnomalyAbortController: (controller: AbortController | null) => ({ controller }),
+ cancelInProgressAnomaly: (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 }),
@@ -495,48 +712,117 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
}),
}),
reducers({
- metricName: ['' as string, { setMetricName: (_, { metricName }) => metricName }],
- // The picked metric's type, latched at pick time (and backfilled if the
- // 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. Sent with
- // queries so a name that exists as several types (e.g. a counter and a
- // gauge) charts only the picked one instead of blending them.
- selectedMetricType: [
- null as OtelMetricTypeEnumApi | null,
- { setSelectedMetricType: (_, { metricType }) => metricType },
- ],
- aggregation: [
- DEFAULT_AGGREGATION as MetricAggregation,
+ // The clause list, active index, and formula live in one reducer so the
+ // active-clause setters can resolve their target synchronously — URL sync
+ // and connected listeners read the updated value in the same dispatch.
+ queryState: [
+ DEFAULT_QUERY_STATE as MetricsViewerQueryState,
{
- setAggregation: (_, { aggregation }) => aggregation,
- setRecommendedAggregation: (_, { aggregation }) => aggregation,
- },
- ],
- // Whether the current aggregation was picked deliberately (by the user, or named in a
- // link) rather than recommended from the metric's type. A deliberate pick holds only
- // until the next metric switch, matching what picking a metric already does.
- aggregationExplicitlySet: [
- false,
- {
- setAggregation: () => true,
- setRecommendedAggregation: () => false,
- setMetricName: () => false,
+ setMetricName: (state, { metricName }) =>
+ // A metric switch drops the previous deliberate aggregation pick,
+ // matching what picking a metric always did.
+ withActiveClause(state, (clause) => ({ ...clause, metricName, aggregationExplicitlySet: false })),
+ // The picked metric's type, latched at pick time (and backfilled if the
+ // 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.
+ setSelectedMetricType: (state, { metricType }) =>
+ withActiveClause(state, (clause) => ({ ...clause, selectedMetricType: metricType })),
+ setAggregation: (state, { aggregation }) =>
+ withActiveClause(state, (clause) => ({ ...clause, aggregation, aggregationExplicitlySet: true })),
+ setRecommendedAggregation: (state, { aggregation }) =>
+ withActiveClause(state, (clause) => ({ ...clause, aggregation, aggregationExplicitlySet: false })),
+ // Attribute keys to split the clause into one series each (e.g. ['service.name', 'env']).
+ setGroupByKeys: (state, { groupByKeys }) =>
+ withActiveClause(state, (clause) => ({ ...clause, groupByKeys })),
+ // The clause's UniversalFilters group; converted into backend matchers by `metricFiltersForGroup`.
+ setFilterGroup: (state, { filterGroup }) =>
+ withActiveClause(state, (clause) => ({ ...clause, filterGroup })),
+ backfillClauses: (state, { updates }) => ({
+ ...state,
+ clauses: state.clauses.map((clause, index) => {
+ const update = updates.find((u) => u.index === index)
+ if (!update) {
+ return clause
+ }
+ return {
+ ...clause,
+ // A backfill never overrides a latched type or a deliberate pick.
+ ...(update.metricType && clause.selectedMetricType === null
+ ? { selectedMetricType: update.metricType }
+ : {}),
+ ...(update.aggregation && !clause.aggregationExplicitlySet
+ ? { aggregation: update.aggregation }
+ : {}),
+ }
+ }),
+ }),
+ addClause: (state) => {
+ const name = nextClauseAlias(state.clauses)
+ if (!name) {
+ return state
+ }
+ // The new clause becomes active so the picker and samples follow it.
+ return {
+ ...state,
+ clauses: [...state.clauses, createViewerClause(name)],
+ activeClauseIndex: state.clauses.length,
+ }
+ },
+ duplicateClause: (state, { index }) => {
+ const source = state.clauses[index]
+ const name = nextClauseAlias(state.clauses)
+ if (!source || !name) {
+ return state
+ }
+ const clauses = [...state.clauses]
+ clauses.splice(index + 1, 0, { ...source, name })
+ return { ...state, clauses, activeClauseIndex: index + 1 }
+ },
+ removeClause: (state, { index }) => {
+ const removed = state.clauses[index]
+ if (state.clauses.length <= 1 || !removed) {
+ return state
+ }
+ const clauses = state.clauses.filter((_, i) => i !== index)
+ const active =
+ state.activeClauseIndex > index ? state.activeClauseIndex - 1 : state.activeClauseIndex
+ // A formula referencing the removed alias can only error; clearing it
+ // keeps the remaining series charted instead of an error banner.
+ // Aliases are word characters, so \b is an exact token boundary.
+ const formula = new RegExp(`\\b${removed.name}\\b`).test(state.formula) ? '' : state.formula
+ return {
+ clauses,
+ activeClauseIndex: Math.max(0, Math.min(active, clauses.length - 1)),
+ formula,
+ }
+ },
+ setActiveClauseIndex: (state, { index }) =>
+ state.clauses[index] ? { ...state, activeClauseIndex: index } : state,
+ setFormula: (state, { formula }) => ({ ...state, formula: sanitizeFormulaInput(formula) }),
+ setClauses: (state, { clauses, formula }) =>
+ clauses.length
+ ? {
+ clauses: clauses.slice(0, MAX_CLAUSES),
+ activeClauseIndex: 0,
+ formula: sanitizeFormulaInput(formula),
+ }
+ : state,
},
],
dateFrom: [DEFAULT_DATE_FROM as string | null, { setDateFrom: (_, { dateFrom }) => dateFrom }],
dateTo: [null as string | null, { setDateTo: (_, { dateTo }) => dateTo }],
liveRefresh: [false, { setLiveRefresh: (_, { liveRefresh }) => liveRefresh }],
- // Attribute keys to split the metric into one series each (e.g. ['service.name', 'env']).
- groupByKeys: [[] as string[], { setGroupByKeys: (_, { groupByKeys }) => groupByKeys }],
// Free-text search backing the group-by attribute-key autocomplete.
groupBySearch: ['' as string, { setGroupBySearch: (_, { groupBySearch }) => groupBySearch }],
- // The filter bar's UniversalFilters group; converted into backend matchers by `queryFilters`.
- filterGroup: [DEFAULT_UNIVERSAL_GROUP_FILTER, { setFilterGroup: (_, { filterGroup }) => filterGroup }],
queryAbortController: [
null as AbortController | null,
{ setQueryAbortController: (_, { controller }) => controller },
],
+ anomalyAbortController: [
+ null as AbortController | null,
+ { setAnomalyAbortController: (_, { controller }) => controller },
+ ],
displayType: [
DEFAULT_DISPLAY_TYPE as MetricsDisplayType,
{ setDisplayType: (_, { displayType }) => displayType },
@@ -606,131 +892,156 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
// `queryResultsLoading`, which drops mid-refetch and flashes the empty state.
queryLoading: [false as boolean, abortResilientLoading('fetchQueryResults')],
}),
- listeners(({ actions, values, cache }) => ({
- // Narrows the metric picker to the filtered services, so it offers only the
- // metrics they report. `setFilterGroup` is the one action that changes the
- // chips, and the scope is compared before pushing so editing an unrelated
- // chip does not refetch the list.
- setFilterGroup: () => {
- if (!objectsEqual(values.selectedServices, values.pickerServices)) {
- actions.setServices(values.selectedServices)
- }
- },
- addAttributeFilter: ({ key, value }) => {
- const inner = values.filterGroup.values[0] as UniversalFiltersGroup
- const existingIndex = inner.values.findIndex(
- (filter) =>
- !isUniversalGroupFilterLike(filter) &&
- 'key' in filter &&
- filter.key === key &&
- 'operator' in filter &&
- filter.operator === PropertyOperator.Exact
- )
- const existing = existingIndex >= 0 ? (inner.values[existingIndex] as UniversalFilterValue) : null
- const existingValues = existing ? toValueStrings('value' in existing ? existing.value : null) : []
- if (existingValues.includes(value)) {
- return
- }
- // Two chips on one key are ANDed, and no series equals both values, so a second pick of
- // the same key widens the chip it already has instead of adding another.
- const chip = {
- type: PropertyFilterType.MetricAttribute,
- key,
- value: [...existingValues, value],
- operator: PropertyOperator.Exact,
- }
- const nextValues = [...inner.values]
- if (existingIndex >= 0) {
- nextValues[existingIndex] = chip as UniversalFilterValue
- } else {
- nextValues.push(chip as UniversalFilterValue)
- }
- actions.setFilterGroup({
- ...values.filterGroup,
- values: [
- { ...inner, values: nextValues as UniversalFiltersGroup['values'] },
- ...values.filterGroup.values.slice(1),
- ],
+ listeners(({ actions, values, cache }) => {
+ // Recovers each clause's type, and the aggregation that follows from it, when the metric
+ // names were set before the picker's list arrived — the shape of a deep link on a cold
+ // load. An already-latched type and an explicitly chosen aggregation are left alone.
+ // Without the aggregation half, a link to a cumulative counter charts the raw running
+ // total rather than its rate: nothing recommended an aggregation while the list was empty.
+ const backfillClauseTypes = (): void => {
+ const updates: MetricsViewerClauseBackfill[] = []
+ values.viewerClauses.forEach((clause, index) => {
+ const trimmedName = clause.metricName.trim()
+ if (!trimmedName) {
+ return
+ }
+ const metricType = values.items.find((item) => item.name === trimmedName)?.metric_type
+ const known = toKnownMetricType(metricType)
+ const recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefined
+ const update: MetricsViewerClauseBackfill = { index }
+ if (known && clause.selectedMetricType === null) {
+ update.metricType = known
+ }
+ // The explicit-pick flag, not a compare against the default, is what holds a
+ // deliberate choice — picking the default value is still a choice.
+ if (recommended && !clause.aggregationExplicitlySet && recommended !== clause.aggregation) {
+ update.aggregation = recommended
+ }
+ if (update.metricType || update.aggregation) {
+ updates.push(update)
+ }
})
- },
- setMetricName: ({ metricName }) => {
- const metricType = values.items.find((item) => item.name === metricName.trim())?.metric_type
- actions.setSelectedMetricType(toKnownMetricType(metricType))
- // 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] : undefined
- if (recommended && recommended !== values.aggregation) {
- actions.setRecommendedAggregation(recommended)
- }
- },
- // Recovers the type, and the aggregation that follows from it, when the metric name was set
- // before the picker's list arrived — the shape of a deep link on a cold load. An
- // already-latched type and an explicitly chosen aggregation are both left alone.
- loadItemsSuccess: () => {
- if (!values.hasMetricName) {
- return
- }
- const metricType = values.items.find((item) => item.name === values.metricName.trim())?.metric_type
- const known = toKnownMetricType(metricType)
- if (known && values.selectedMetricType === null) {
- actions.setSelectedMetricType(known)
- }
- // Without this a link to a cumulative counter charts the raw running total rather than
- // its rate: nothing recommended an aggregation while the list was still empty. The
- // explicit-pick flag, not a compare against the default, is what holds a deliberate
- // choice — picking the default value is still a choice.
- const recommended = metricType ? RECOMMENDED_AGGREGATION_BY_TYPE[metricType] : undefined
- if (recommended && !values.aggregationExplicitlySet && recommended !== values.aggregation) {
- actions.setRecommendedAggregation(recommended)
- }
- },
- saveAsInsightFailure: ({ error }) => {
- lemonToast.error(`Failed to save insight: ${error}`)
- },
- addToDashboard: () => {
- if (!canCreateMetricsInsight() || !values.metricsQueryNode) {
- 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)) {
- actions.openAddToDashboardModal()
- return
- }
- actions.saveAsInsight()
- },
- saveAsInsightSuccess: ({ savedInsight }) => {
- if (savedInsight && values.pendingAddToDashboard) {
- actions.openAddToDashboardModal()
+ if (updates.length) {
+ actions.backfillClauses(updates)
}
- },
- setGroupBySearch: () => {
- actions.loadAttributeKeyOptions({})
- },
- cancelInProgressQuery: ({ controller }) => {
- if (values.queryAbortController !== null) {
- // An AbortError-named DOMException (not a bare string) is what api.ts and the global
- // loader onFailure recognize as a cancellation, so a superseded query is swallowed
- // rather than logged/captured as a real error.
- values.queryAbortController.abort(new DOMException(NEW_QUERY_STARTED_ERROR_MESSAGE, 'AbortError'))
- }
- actions.setQueryAbortController(controller)
- },
- setLiveRefresh: ({ liveRefresh }) => {
- if (!liveRefresh) {
- cache.disposables.dispose(LIVE_REFRESH_KEY)
- return
+ }
+ // Narrows the metric picker to the active clause's service chips, so it offers
+ // only the metrics they report. The scope is compared before pushing so an
+ // unrelated edit does not refetch the list.
+ const syncPickerServices = (): void => {
+ if (!objectsEqual(values.selectedServices, values.pickerServices)) {
+ actions.setServices(values.selectedServices)
}
- // pauseOnPageHidden (default) stops polling on a hidden tab and resumes on focus.
- cache.disposables.add(() => {
- const intervalId = setInterval(() => {
- actions.fetchQueryResults({})
- actions.fetchAnomaly({})
- }, LIVE_REFRESH_MS)
- return () => clearInterval(intervalId)
- }, LIVE_REFRESH_KEY)
- },
- })),
+ }
+ return {
+ // `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,
+ addAttributeFilter: ({ key, value }) => {
+ const inner = values.filterGroup.values[0] as UniversalFiltersGroup
+ const existingIndex = inner.values.findIndex(
+ (filter) =>
+ !isUniversalGroupFilterLike(filter) &&
+ 'key' in filter &&
+ filter.key === key &&
+ 'operator' in filter &&
+ filter.operator === PropertyOperator.Exact
+ )
+ const existing = existingIndex >= 0 ? (inner.values[existingIndex] as UniversalFilterValue) : null
+ const existingValues = existing ? toValueStrings('value' in existing ? existing.value : null) : []
+ if (existingValues.includes(value)) {
+ return
+ }
+ // Two chips on one key are ANDed, and no series equals both values, so a second pick of
+ // the same key widens the chip it already has instead of adding another.
+ const chip = {
+ type: PropertyFilterType.MetricAttribute,
+ key,
+ value: [...existingValues, value],
+ operator: PropertyOperator.Exact,
+ }
+ const nextValues = [...inner.values]
+ if (existingIndex >= 0) {
+ nextValues[existingIndex] = chip as UniversalFilterValue
+ } else {
+ nextValues.push(chip as UniversalFilterValue)
+ }
+ actions.setFilterGroup({
+ ...values.filterGroup,
+ values: [
+ { ...inner, values: nextValues as UniversalFiltersGroup['values'] },
+ ...values.filterGroup.values.slice(1),
+ ],
+ })
+ },
+ setMetricName: ({ metricName }) => {
+ const metricType = values.items.find((item) => item.name === metricName.trim())?.metric_type
+ actions.setSelectedMetricType(toKnownMetricType(metricType))
+ // 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] : undefined
+ if (recommended && recommended !== values.aggregation) {
+ actions.setRecommendedAggregation(recommended)
+ }
+ },
+ loadItemsSuccess: backfillClauseTypes,
+ // A URL restore replaces every clause at once and never ran the pick-time
+ // latch, so it needs the same backfill against whatever the picker has.
+ setClauses: () => {
+ backfillClauseTypes()
+ syncPickerServices()
+ },
+ saveAsInsightFailure: ({ error }) => {
+ lemonToast.error(`Failed to save insight: ${error}`)
+ },
+ addToDashboard: () => {
+ if (!canCreateMetricsInsight() || !values.metricsQueryNode) {
+ 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)) {
+ actions.openAddToDashboardModal()
+ return
+ }
+ actions.saveAsInsight()
+ },
+ saveAsInsightSuccess: ({ savedInsight }) => {
+ if (savedInsight && values.pendingAddToDashboard) {
+ actions.openAddToDashboardModal()
+ }
+ },
+ setGroupBySearch: () => {
+ actions.loadAttributeKeyOptions({})
+ },
+ cancelInProgressQuery: ({ controller }) => {
+ abortPrevious(values.queryAbortController)
+ actions.setQueryAbortController(controller)
+ },
+ cancelInProgressAnomaly: ({ controller }) => {
+ abortPrevious(values.anomalyAbortController)
+ actions.setAnomalyAbortController(controller)
+ },
+ setLiveRefresh: ({ liveRefresh }) => {
+ if (!liveRefresh) {
+ cache.disposables.dispose(LIVE_REFRESH_KEY)
+ return
+ }
+ // pauseOnPageHidden (default) stops polling on a hidden tab and resumes on focus.
+ cache.disposables.add(() => {
+ const intervalId = setInterval(() => {
+ actions.fetchQueryResults({})
+ actions.fetchAnomaly({})
+ }, LIVE_REFRESH_MS)
+ return () => clearInterval(intervalId)
+ }, LIVE_REFRESH_KEY)
+ },
+ }
+ }),
loaders(({ values, actions }) => ({
// Backs the group-by attribute-key autocomplete. Scoped to the viewer's window so
// suggestions match the data on screen; debounced to match the chart fetch cadence.
@@ -762,8 +1073,8 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
if (!canViewMetrics()) {
return []
}
- const trimmedName = values.metricName.trim()
- if (!trimmedName) {
+ const queryPayload = values.queryPayload
+ if (!queryPayload) {
return []
}
const dateFromISO = resolveDate(values.dateFrom)
@@ -778,15 +1089,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
String(values.currentTeamId),
{
query: {
- metricName: trimmedName,
- aggregation: values.aggregation,
- ...(values.selectedMetricType ? { metricType: values.selectedMetricType } : {}),
+ ...queryPayload,
dateFrom: dateFromISO,
...(dateToISO ? { dateTo: dateToISO } : {}),
- ...(values.groupByKeys.length
- ? { groupBy: values.groupByKeys.map((key) => ({ key })) }
- : {}),
- ...(values.queryFilters.length ? { filters: values.queryFilters } : {}),
},
},
{ signal: controller.signal }
@@ -809,7 +1114,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
return null
}
const insight = await insightsApi.create({
- name: `${values.metricName} (${values.aggregation})`,
+ name: insightNameForViewerQuery(values.namedClauses, values.formula),
query,
saved: true,
})
@@ -835,9 +1140,14 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
if (!canViewMetrics()) {
return null
}
- const trimmedName = values.metricName.trim()
+ // Null while suppressed (multi-series or formula): a badge computed from
+ // one input clause would be attributed to the wrong chart line.
+ const anomalyQuery = values.anomalyQuery
+ if (!anomalyQuery) {
+ return null
+ }
const fromISO = resolveDate(values.dateFrom)
- if (!trimmedName || !fromISO) {
+ if (!fromISO) {
return null
}
const toISO = resolveDate(values.dateTo) ?? dayjs().toISOString()
@@ -849,23 +1159,97 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
.subtract(spanMs * ANOMALY_WINDOW_FRACTION, 'ms')
.toISOString()
await breakpoint(300)
- const report = await metricsCharacterizeCreate(String(values.currentTeamId), {
- query: {
- metricName: trimmedName,
- aggregation: values.aggregation,
- anomalyFrom,
- anomalyTo: toISO,
- ...(values.queryFilters.length ? { filters: values.queryFilters } : {}),
+ const controller = new AbortController()
+ actions.cancelInProgressAnomaly(controller)
+ const report = await metricsCharacterizeCreate(
+ String(values.currentTeamId),
+ {
+ query: {
+ ...anomalyQuery,
+ anomalyFrom,
+ anomalyTo: toISO,
+ },
},
- })
+ { signal: controller.signal }
+ )
breakpoint()
+ actions.setAnomalyAbortController(null)
return report
},
},
],
})),
selectors({
- hasMetricName: [(s) => [s.metricName], (metricName: string) => metricName.trim().length > 0],
+ viewerClauses: [(s) => [s.queryState], (queryState: MetricsViewerQueryState) => queryState.clauses],
+ activeClauseIndex: [
+ (s) => [s.queryState],
+ (queryState: MetricsViewerQueryState) => queryState.activeClauseIndex,
+ ],
+ formula: [(s) => [s.queryState], (queryState: MetricsViewerQueryState) => queryState.formula],
+ activeClause: [
+ (s) => [s.viewerClauses, s.activeClauseIndex],
+ (clauses: MetricsViewerClause[], activeClauseIndex: number): MetricsViewerClause =>
+ clauses[activeClauseIndex] ?? clauses[0],
+ ],
+ // The single-clause vocabulary, kept as selectors over the active clause so
+ // everything that followed the viewer's one metric still works unchanged.
+ metricName: [(s) => [s.activeClause], (activeClause: MetricsViewerClause) => activeClause.metricName],
+ selectedMetricType: [
+ (s) => [s.activeClause],
+ (activeClause: MetricsViewerClause) => activeClause.selectedMetricType,
+ ],
+ aggregation: [(s) => [s.activeClause], (activeClause: MetricsViewerClause) => activeClause.aggregation],
+ groupByKeys: [(s) => [s.activeClause], (activeClause: MetricsViewerClause) => activeClause.groupByKeys],
+ filterGroup: [(s) => [s.activeClause], (activeClause: MetricsViewerClause) => activeClause.filterGroup],
+ // The clauses that actually query something — a just-added blank row is
+ // unsaved work in progress and stays out of every request and serialization.
+ namedClauses: [
+ (s) => [s.viewerClauses],
+ (clauses: MetricsViewerClause[]): MetricsViewerClause[] =>
+ clauses.filter((clause) => clause.metricName.trim().length > 0),
+ ],
+ hasMetricName: [(s) => [s.namedClauses], (namedClauses: MetricsViewerClause[]) => namedClauses.length > 0],
+ // The chart request minus the date range (resolved at fetch time). The fetch
+ // loader sends this object verbatim, so the fingerprint below can't drift from
+ // the real payload. Null when nothing queries anything yet.
+ queryPayload: [
+ (s) => [s.namedClauses, s.formula],
+ (namedClauses: MetricsViewerClause[], formula: string): MetricsQueryRequestBody | null =>
+ namedClauses.length
+ ? { clauses: namedClauses.map(clauseToApiClause), ...(formula ? { formula } : {}) }
+ : null,
+ ],
+ // Effect key for the chart fetch: string-valued so equal queries compare equal,
+ // and a blank-row add/remove (which changes `viewerClauses` but not the request)
+ // doesn't refetch the chart and cascade into samples/exemplar reloads.
+ queryFingerprint: [
+ (s) => [s.queryPayload],
+ (queryPayload: MetricsQueryRequestBody | null): string => JSON.stringify(queryPayload),
+ ],
+ // The characterize request minus the anomaly window, null when the badge is
+ // suppressed: with several clauses (or a formula result) there is no single
+ // input series it could honestly describe. Sent verbatim by the loader.
+ anomalyQuery: [
+ (s) => [s.namedClauses, s.formula],
+ (namedClauses: MetricsViewerClause[], formula: string): MetricsAnomalyRequestBody | null => {
+ if (namedClauses.length !== 1 || formula) {
+ return null
+ }
+ const clause = namedClauses[0]
+ const filters = metricFiltersForGroup(clause.filterGroup)
+ return {
+ metricName: clause.metricName.trim(),
+ aggregation: clause.aggregation,
+ ...(filters.length ? { filters } : {}),
+ }
+ },
+ ],
+ // Same idea as queryFingerprint: the badge only refetches when its own request
+ // changes — a group-by edit redraws the chart but not the characterization.
+ anomalyFingerprint: [
+ (s) => [s.anomalyQuery],
+ (anomalyQuery: MetricsAnomalyRequestBody | null): string => JSON.stringify(anomalyQuery),
+ ],
// 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: [
@@ -885,56 +1269,22 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
],
// 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.
metricsQueryNode: [
- (s) => [
- s.metricName,
- s.aggregation,
- s.selectedMetricType,
- s.dateFrom,
- s.dateTo,
- s.groupByKeys,
- s.queryFilters,
- s.metricsDisplay,
- ],
+ (s) => [s.namedClauses, s.formula, s.dateFrom, s.dateTo, s.metricsDisplay],
(
- metricName: string,
- aggregation: MetricAggregation,
- selectedMetricType: OtelMetricTypeEnumApi | null,
+ namedClauses: MetricsViewerClause[],
+ formula: string,
dateFrom: string | null,
dateTo: string | null,
- groupByKeys: string[],
- queryFilters: _MetricFilterApi[],
metricsDisplay: MetricsDisplaySettings | undefined
): MetricsQuery | null => {
- const trimmedName = metricName.trim()
- if (!trimmedName) {
+ if (!namedClauses.length) {
return null
}
- const clause: MetricsQueryClause = {
- name: 'a',
- metricName: trimmedName,
- aggregation: aggregation === 'p95' ? 'quantile' : aggregation,
- // Pins the OTel type so the saved tile can't blend same-named
- // series of different types (mirrors the live viewer's query).
- ...(selectedMetricType ? { metricType: selectedMetricType } : {}),
- ...(aggregation === 'p95' ? { quantile: 0.95 } : {}),
- ...(queryFilters.length
- ? {
- filters: queryFilters.map(
- (f): MetricsQueryFilter => ({
- key: f.key,
- op: f.op as MetricsQueryFilter['op'],
- value: f.value,
- })
- ),
- }
- : {}),
- ...(groupByKeys.length ? { groupBy: groupByKeys.map((key) => ({ key })) } : {}),
- }
return {
kind: NodeKind.MetricsQuery,
- clauses: [clause],
+ clauses: namedClauses.map(clauseToNodeClause),
+ ...(formula ? { formula } : {}),
dateRange: {
date_from: dateFrom ?? DEFAULT_DATE_FROM,
...(dateTo ? { date_to: dateTo } : {}),
@@ -943,19 +1293,17 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
}
},
],
+ // The active clause's filter bar as backend matchers — what the samples panel sends.
queryFilters: [
- (s) => [s.filterGroup],
- (filterGroup: UniversalFiltersGroup): _MetricFilterApi[] =>
- flattenFilterValues(filterGroup)
- .map(propertyFilterToMetricFilter)
- .filter((f): f is _MetricFilterApi => f !== null),
+ (s) => [s.activeClause],
+ (activeClause: MetricsViewerClause): _MetricFilterApi[] => metricFiltersForGroup(activeClause.filterGroup),
],
// Services the metric picker is narrowed to, so it only offers metrics the
// filtered services actually report. Empty means "every service".
selectedServices: [
- (s) => [s.filterGroup],
- (filterGroup: UniversalFiltersGroup): string[] => {
- const chips = flattenFilterValues(filterGroup).filter(
+ (s) => [s.activeClause],
+ (activeClause: MetricsViewerClause): string[] => {
+ const chips = flattenFilterValues(activeClause.filterGroup).filter(
(filter) => 'key' in filter && filter.key === SERVICE_NAME_KEY
)
// Two service chips are ANDed, which no single IN list expresses, so
@@ -986,7 +1334,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
}),
],
// All series rendered as chart lines (a group-by query returns one series per label combination).
- // `MetricsSeriesChart` owns naming and colors; this only bridges the API's snake_case field.
+ // `MetricsSeriesChart` owns naming and colors; this only bridges the API's snake_case fields.
chartSeries: [
(s) => [s.queryResults],
(results: MetricsViewerSeries[]): MetricsChartSeries[] =>
@@ -994,13 +1342,14 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
labels: series.labels,
points: series.points,
metricName: series.metric_name,
+ clause: series.clause,
})),
],
- // Whether the chart has anything to draw. A metric can return a series with no points
+ // Whether the chart has anything to draw. A query can return series with no points
// in the selected window, which is the empty state rather than a plottable result.
hasResults: [
(s) => [s.queryResults],
- (results: MetricsViewerSeries[]): boolean => (results[0]?.points.length ?? 0) > 0,
+ (results: MetricsViewerSeries[]): boolean => results.some((series) => series.points.length > 0),
],
// The label values behind the current anomaly, ranked. Empty for an ungrouped metric or
// when nothing stood out, which the panel reports rather than hiding.
diff --git a/products/metrics/frontend/metricsSceneLogic.test.ts b/products/metrics/frontend/metricsSceneLogic.test.ts
index eb3685d06889..2be7ad2d768b 100644
--- a/products/metrics/frontend/metricsSceneLogic.test.ts
+++ b/products/metrics/frontend/metricsSceneLogic.test.ts
@@ -14,6 +14,7 @@ import {
import { metricsQueryCreate, metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'
+import { metricsViewerLogic } from './components/metricsViewerLogic'
import { metricsSceneLogic } from './metricsSceneLogic'
jest.mock('products/metrics/frontend/generated/api', () => ({
@@ -117,6 +118,98 @@ describe('metricsSceneLogic', () => {
expect(logic.values[valueKey as keyof typeof logic.values]).toEqual(expected)
})
+ it('restores multiple clauses and a formula from the clauses URL param', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', {
+ activeTab: 'viewer',
+ clauses: JSON.stringify([
+ { name: 'a', metricName: 'requests_total', aggregation: 'rate' },
+ {
+ name: 'b',
+ metricName: 'queue_depth',
+ aggregation: 'avg',
+ metricType: 'gauge',
+ groupBy: ['env'],
+ },
+ ]),
+ formula: 'a / b',
+ })
+ }).toFinishAllListeners()
+
+ expect(logic.values.viewerClauses).toEqual([
+ expect.objectContaining({ name: 'a', metricName: 'requests_total', aggregation: 'rate' }),
+ expect.objectContaining({
+ name: 'b',
+ metricName: 'queue_depth',
+ aggregation: 'avg',
+ selectedMetricType: 'gauge',
+ groupByKeys: ['env'],
+ }),
+ ])
+ expect(logic.values.formula).toEqual('a / b')
+ })
+
+ it('a legacy single-metric link collapses multi-clause state', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', {
+ clauses: JSON.stringify([
+ { name: 'a', metricName: 'requests_total', aggregation: 'rate' },
+ { name: 'b', metricName: 'queue_depth', aggregation: 'avg' },
+ ]),
+ formula: 'a / b',
+ })
+ }).toFinishAllListeners()
+ expect(logic.values.viewerClauses).toHaveLength(2)
+
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', { metricName: 'queue_depth' })
+ }).toFinishAllListeners()
+
+ expect(logic.values.viewerClauses).toHaveLength(1)
+ expect(logic.values.metricName).toEqual('queue_depth')
+ expect(logic.values.formula).toEqual('')
+ })
+
+ // An invalid clauses param must not fall through to the legacy branch — that
+ // would collapse the multi-series state on screen to one blank clause.
+ it('an invalid clauses param leaves multi-series state untouched', async () => {
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', {
+ clauses: JSON.stringify([
+ { name: 'a', metricName: 'requests_total', aggregation: 'rate' },
+ { name: 'b', metricName: 'queue_depth', aggregation: 'avg' },
+ ]),
+ })
+ }).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', { clauses: '{corrupted' })
+ }).toFinishAllListeners()
+
+ expect(logic.values.viewerClauses).toHaveLength(2)
+ expect(logic.values.metricName).toEqual('requests_total')
+ })
+
+ // The clauses param is attacker-controlled JSON; any invalid entry must reject the
+ // whole param instead of reaching the viewer half-validated.
+ it.each([
+ ['unparsable JSON', '{not json'],
+ ['not an array', '{"a":1}'],
+ ['a clause without a metric', '[{"name":"a","aggregation":"sum"}]'],
+ ['an unknown aggregation', '[{"name":"a","metricName":"x","aggregation":"nope"}]'],
+ [
+ 'duplicate aliases',
+ '[{"name":"a","metricName":"x","aggregation":"sum"},{"name":"a","metricName":"y","aggregation":"sum"}]',
+ ],
+ ])('ignores a malformed clauses param (%s)', async (_, urlValue) => {
+ const before = logic.values.viewerClauses
+ await expectLogic(logic, () => {
+ router.actions.push('/metrics', { clauses: urlValue })
+ }).toFinishAllListeners()
+
+ expect(logic.values.viewerClauses).toEqual(before)
+ })
+
it.each([
['unparsable JSON', '{not valid json'],
// kea-router pre-parses JSON-looking params, so these arrive as real values
@@ -169,6 +262,58 @@ describe('metricsSceneLogic', () => {
expect(router.values.searchParams).toMatchObject({ metricName: 'requests_total' })
})
+ // The two URL encodings must never disagree: multi-series/formula state writes
+ // `clauses` and removes the legacy params, and collapsing back restores them.
+ it('switches between the legacy and clauses encodings as series come and go', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setMetricName('requests_total')
+ }).toFinishAllListeners()
+ expect(router.values.searchParams).toMatchObject({ metricName: 'requests_total' })
+ expect(router.values.searchParams).not.toHaveProperty('clauses')
+
+ metricsViewerLogic.actions.addClause()
+ await expectLogic(logic, () => {
+ metricsViewerLogic.actions.setMetricName('queue_depth')
+ }).toFinishAllListeners()
+ expect(router.values.searchParams).not.toHaveProperty('metricName')
+ expect(router.values.searchParams.clauses).toEqual([
+ expect.objectContaining({ name: 'a', metricName: 'requests_total' }),
+ expect.objectContaining({ name: 'b', metricName: 'queue_depth' }),
+ ])
+
+ await expectLogic(logic, () => {
+ metricsViewerLogic.actions.setFormula('a / b')
+ }).toFinishAllListeners()
+ expect(router.values.searchParams.formula).toEqual('a / b')
+
+ await expectLogic(logic, () => {
+ metricsViewerLogic.actions.setFormula('')
+ metricsViewerLogic.actions.removeClause(1)
+ }).toFinishAllListeners()
+ expect(router.values.searchParams).not.toHaveProperty('clauses')
+ expect(router.values.searchParams).not.toHaveProperty('formula')
+ expect(router.values.searchParams).toMatchObject({ metricName: 'requests_total' })
+ })
+
+ // With a blank just-added row focused, the active clause is empty while the chart
+ // still shows the named one — the legacy encoding must serialize the named clause,
+ // or editing the blank row drops the metric from the link.
+ it('keeps the named clause in the URL while a blank added row is focused', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setMetricName('requests_total')
+ }).toFinishAllListeners()
+
+ metricsViewerLogic.actions.addClause()
+ await expectLogic(logic, () => {
+ logic.actions.setAggregation('rate')
+ }).toFinishAllListeners()
+
+ expect(router.values.searchParams).toMatchObject({
+ metricName: 'requests_total',
+ aggregation: 'increase',
+ })
+ })
+
it('keeps viewer params in the URL when switching tabs', async () => {
await expectLogic(logic, () => {
logic.actions.setMetricName('requests_total')
diff --git a/products/metrics/frontend/metricsSceneLogic.tsx b/products/metrics/frontend/metricsSceneLogic.tsx
index 8c3419e2853b..4a9f3c04df00 100644
--- a/products/metrics/frontend/metricsSceneLogic.tsx
+++ b/products/metrics/frontend/metricsSceneLogic.tsx
@@ -6,6 +6,7 @@ import { syncSearchParams, updateSearchParams } from '@posthog/products-error-tr
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/constants'
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
+import { tryJsonParse } from 'lib/utils/json'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual } from 'lib/utils/objects'
import { parseTagsFilter } from 'lib/utils/url'
@@ -21,9 +22,13 @@ import { OtelMetricTypeEnumApi } from 'products/metrics/frontend/generated/api.s
import {
DEFAULT_AGGREGATION,
DEFAULT_DATE_FROM,
- METRIC_AGGREGATIONS,
+ MAX_CLAUSES,
MetricAggregation,
+ MetricsViewerClause,
+ createViewerClause,
+ isMetricAggregation,
metricsViewerLogic,
+ sanitizeFormulaInput,
toKnownMetricType,
} from './components/metricsViewerLogic'
@@ -46,24 +51,114 @@ const isValidFilterGroup = (group: any): group is UniversalFiltersGroup =>
group.values.length > 0 &&
group.values.every(isValidInnerGroup)
+// Legacy single-clause params, written for one plain clause so old links stay short
+// and other products' link builders (metricsLinks.ts) keep working unchanged.
+const LEGACY_VIEWER_PARAMS = ['metricName', 'metricType', 'aggregation', 'groupBy', 'filterGroup'] as const
+
+// A clause's alias must satisfy the backend's identifier rules (formulas reference it).
+const CLAUSE_NAME_PATTERN = /^[a-z][a-z0-9_]{0,63}$/
+
+// The URL codec's clause shape: only the fields a link needs — no active index, no
+// explicit-pick flag, defaults omitted. Parse and serialize both speak this type, so a
+// field added to one direction fails to compile until the other carries it too.
+interface UrlViewerClause {
+ name: string
+ metricName: string
+ aggregation: MetricAggregation
+ metricType?: OtelMetricTypeEnumApi
+ groupBy?: string[]
+ filterGroup?: UniversalFiltersGroup
+}
+
+const serializeViewerClause = (clause: MetricsViewerClause): UrlViewerClause => ({
+ name: clause.name,
+ metricName: clause.metricName.trim(),
+ aggregation: clause.aggregation,
+ ...(clause.selectedMetricType ? { metricType: clause.selectedMetricType } : {}),
+ ...(clause.groupByKeys.length ? { groupBy: clause.groupByKeys } : {}),
+ ...(objectsEqual(clause.filterGroup, DEFAULT_UNIVERSAL_GROUP_FILTER) ? {} : { filterGroup: clause.filterGroup }),
+})
+
+// The `clauses` param is attacker-controlled JSON (kea-router pre-parses it), so every
+// field is validated before it can reach the viewer; any invalid entry rejects the whole
+// param, mirroring how a malformed legacy filterGroup is ignored.
+const parseClausesParam = (raw: unknown): MetricsViewerClause[] | null => {
+ // The Array.isArray check below rejects tryJsonParse's undefined fallback.
+ const parsed = typeof raw === 'string' ? tryJsonParse(raw) : raw
+ if (!Array.isArray(parsed) || parsed.length === 0 || parsed.length > MAX_CLAUSES) {
+ return null
+ }
+ const seenNames = new Set<string>()
+ const clauses: MetricsViewerClause[] = []
+ for (const item of parsed) {
+ if (typeof item !== 'object' || item === null) {
+ return null
+ }
+ const name = typeof item.name === 'string' && CLAUSE_NAME_PATTERN.test(item.name) ? item.name : null
+ const metricName = typeof item.metricName === 'string' ? item.metricName : ''
+ if (!name || seenNames.has(name) || !metricName.trim()) {
+ return null
+ }
+ seenNames.add(name)
+ if (!isMetricAggregation(item.aggregation)) {
+ return null
+ }
+ const groupByKeys =
+ Array.isArray(item.groupBy) && item.groupBy.every((key: unknown) => typeof key === 'string')
+ ? (item.groupBy as string[])
+ : []
+ clauses.push({
+ name,
+ metricName,
+ selectedMetricType: toKnownMetricType(typeof item.metricType === 'string' ? item.metricType : undefined),
+ aggregation: item.aggregation,
+ // An aggregation named in a link is a deliberate choice — the picker's
+ // late type backfill must not override it with the recommendation.
+ aggregationExplicitlySet: true,
+ filterGroup: isValidFilterGroup(item.filterGroup) ? item.filterGroup : DEFAULT_UNIVERSAL_GROUP_FILTER,
+ groupByKeys,
+ })
+ }
+ return clauses
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSceneLogicValues {
aggregation: MetricAggregation // metricsViewerLogic
dateFrom: string | null // metricsViewerLogic
dateTo: string | null // metricsViewerLogic
filterGroup: UniversalFiltersGroup // metricsViewerLogic
+ formula: string // metricsViewerLogic
groupByKeys: string[] // metricsViewerLogic
metricName: string // metricsViewerLogic
+ namedClauses: MetricsViewerClause[] // metricsViewerLogic
selectedMetricType: OtelMetricTypeEnumApi | null // metricsViewerLogic
+ viewerClauses: MetricsViewerClause[] // metricsViewerLogic
activeTab: MetricsSceneActiveTab
isRestoringFromUrl: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface metricsSceneLogicActions {
+ backfillClauses: (updates: import('./components/metricsViewerLogic').MetricsViewerClauseBackfill[]) => {
+ updates: import('./components/metricsViewerLogic').MetricsViewerClauseBackfill[]
+ } // metricsViewerLogic
+ duplicateClause: (index: number) => {
+ index: number
+ } // metricsViewerLogic
+ removeClause: (index: number) => {
+ index: number
+ } // metricsViewerLogic
setAggregation: (aggregation: MetricAggregation) => {
aggregation: MetricAggregation
} // metricsViewerLogic
+ setClauses: (
+ clauses: MetricsViewerClause[],
+ formula: string
+ ) => {
+ clauses: MetricsViewerClause[]
+ formula: string
+ } // metricsViewerLogic
setDateFrom: (dateFrom: string | null) => {
dateFrom: string | null
} // metricsViewerLogic
@@ -73,6 +168,9 @@ export interface metricsSceneLogicActions {
setFilterGroup: (filterGroup: UniversalFiltersGroup) => {
filterGroup: UniversalFiltersGroup
} // metricsViewerLogic
+ setFormula: (formula: string) => {
+ formula: string
+ } // metricsViewerLogic
setGroupByKeys: (groupByKeys: string[]) => {
groupByKeys: string[]
} // metricsViewerLogic
@@ -106,7 +204,18 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
connect(() => ({
values: [
metricsViewerLogic,
- ['metricName', 'selectedMetricType', 'aggregation', 'dateFrom', 'dateTo', 'groupByKeys', 'filterGroup'],
+ [
+ 'metricName',
+ 'selectedMetricType',
+ 'aggregation',
+ 'dateFrom',
+ 'dateTo',
+ 'groupByKeys',
+ 'filterGroup',
+ 'viewerClauses',
+ 'namedClauses',
+ 'formula',
+ ],
],
actions: [
metricsViewerLogic,
@@ -119,6 +228,11 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
'setDateTo',
'setGroupByKeys',
'setFilterGroup',
+ 'setClauses',
+ 'setFormula',
+ 'removeClause',
+ 'duplicateClause',
+ 'backfillClauses',
],
],
})),
@@ -163,30 +277,68 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
) {
actions.setActiveTab(requested as MetricsSceneActiveTab)
}
- // metricName first: its listener latches the metric type and a recommended
- // aggregation, which the explicit URL params below then override.
- const metricName = params.metricName != null ? String(params.metricName) : ''
- if (metricName !== values.metricName) {
- actions.setMetricName(metricName)
- }
- const metricType = toKnownMetricType(
- typeof params.metricType === 'string' ? params.metricType : undefined
- )
- if (metricType && metricType !== values.selectedMetricType) {
- actions.setSelectedMetricType(metricType)
- }
- const aggregation =
- typeof params.aggregation === 'string' &&
- METRIC_AGGREGATIONS.includes(params.aggregation as MetricAggregation)
- ? (params.aggregation as MetricAggregation)
- : null
- if (aggregation && aggregation !== values.aggregation) {
- actions.setAggregation(aggregation)
- } else if (!aggregation && !metricName && values.aggregation !== DEFAULT_AGGREGATION) {
- // A bare URL resets to the clean-slate default. With a metric but no
- // aggregation param (a hand-written link), the recommended aggregation
- // latched by setMetricName stays.
- actions.setAggregation(DEFAULT_AGGREGATION)
+ if (params.clauses) {
+ // A present-but-invalid clauses param is ignored outright, like a malformed
+ // filterGroup — falling through to the legacy branch would collapse the
+ // multi-series state on screen.
+ const parsedClauses = parseClausesParam(params.clauses)
+ if (parsedClauses) {
+ const formula = typeof params.formula === 'string' ? sanitizeFormulaInput(params.formula) : ''
+ if (
+ formula !== values.formula ||
+ !objectsEqual(
+ parsedClauses.map(serializeViewerClause),
+ values.namedClauses.map(serializeViewerClause)
+ )
+ ) {
+ actions.setClauses(parsedClauses, formula)
+ }
+ }
+ } else {
+ // A legacy (single-clause) link means "show this one metric": collapse
+ // any multi-clause state first, so the appliers below land on clause 'a'.
+ if (values.viewerClauses.length > 1) {
+ actions.setClauses([createViewerClause('a')], '')
+ } else if (values.formula) {
+ actions.setFormula('')
+ }
+ // metricName first: its listener latches the metric type and a recommended
+ // aggregation, which the explicit URL params below then override.
+ const metricName = params.metricName != null ? String(params.metricName) : ''
+ if (metricName !== values.metricName) {
+ actions.setMetricName(metricName)
+ }
+ const metricType = toKnownMetricType(
+ typeof params.metricType === 'string' ? params.metricType : undefined
+ )
+ if (metricType && metricType !== values.selectedMetricType) {
+ actions.setSelectedMetricType(metricType)
+ }
+ const aggregation = isMetricAggregation(params.aggregation) ? params.aggregation : null
+ if (aggregation && aggregation !== values.aggregation) {
+ actions.setAggregation(aggregation)
+ } else if (!aggregation && !metricName && values.aggregation !== DEFAULT_AGGREGATION) {
+ // A bare URL resets to the clean-slate default. With a metric but no
+ // aggregation param (a hand-written link), the recommended aggregation
+ // latched by setMetricName stays.
+ actions.setAggregation(DEFAULT_AGGREGATION)
+ }
+ const groupByKeys = parseTagsFilter(params.groupBy) ?? []
+ if (!objectsEqual(groupByKeys, values.groupByKeys)) {
+ actions.setGroupByKeys(groupByKeys)
+ }
+ if (params.filterGroup) {
+ // Malformed filterGroup JSON parses to undefined and fails validation.
+ const filterGroup =
+ typeof params.filterGroup === 'string'
+ ? tryJsonParse(params.filterGroup)
+ : params.filterGroup
+ if (isValidFilterGroup(filterGroup) && !objectsEqual(filterGroup, values.filterGroup)) {
+ actions.setFilterGroup(filterGroup)
+ }
+ } else if (!objectsEqual(DEFAULT_UNIVERSAL_GROUP_FILTER, values.filterGroup)) {
+ actions.setFilterGroup(DEFAULT_UNIVERSAL_GROUP_FILTER)
+ }
}
const dateFrom =
typeof params.dateFrom === 'string' && params.dateFrom ? params.dateFrom : DEFAULT_DATE_FROM
@@ -197,23 +349,6 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
if (dateTo !== values.dateTo) {
actions.setDateTo(dateTo)
}
- const groupByKeys = parseTagsFilter(params.groupBy) ?? []
- if (!objectsEqual(groupByKeys, values.groupByKeys)) {
- actions.setGroupByKeys(groupByKeys)
- }
- if (params.filterGroup) {
- try {
- const filterGroup =
- typeof params.filterGroup === 'string' ? JSON.parse(params.filterGroup) : params.filterGroup
- if (isValidFilterGroup(filterGroup) && !objectsEqual(filterGroup, values.filterGroup)) {
- actions.setFilterGroup(filterGroup)
- }
- } catch {
- // Ignore malformed filterGroup JSON in the URL
- }
- } else if (!objectsEqual(DEFAULT_UNIVERSAL_GROUP_FILTER, values.filterGroup)) {
- actions.setFilterGroup(DEFAULT_UNIVERSAL_GROUP_FILTER)
- }
} finally {
actions.setRestoringFromUrl(false)
}
@@ -232,20 +367,47 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
cache.isSyncingUrl = true
const result = syncSearchParams(router, (params: Params) => {
updateSearchParams(params, 'activeTab', values.activeTab, DEFAULT_ACTIVE_TAB)
- updateSearchParams(params, 'metricName', values.metricName, '')
- updateSearchParams(params, 'metricType', values.selectedMetricType, null)
- if (values.metricName) {
- // Never dropped while a metric is picked: 'sum' is both the default and a
- // valid explicit choice, so a link that omitted it would restore with the
- // metric type's recommended aggregation instead of the one on screen.
- params.aggregation = values.aggregation
+ // A blank just-added row is unsaved work in progress, not link state.
+ const namedClauses = values.namedClauses
+ const useClausesEncoding = namedClauses.length > 1 || (!!values.formula && namedClauses.length > 0)
+ if (useClausesEncoding) {
+ // The two encodings must never disagree, so whichever one is written
+ // deletes the other's params.
+ params.clauses = namedClauses.map(serializeViewerClause)
+ updateSearchParams(params, 'formula', values.formula, '')
+ for (const legacyParam of LEGACY_VIEWER_PARAMS) {
+ delete params[legacyParam]
+ }
} else {
- delete params.aggregation
+ delete params.clauses
+ delete params.formula
+ // Serialize the named clause, not the focused one — with a blank just-added
+ // row focused, the active clause is empty while the chart still shows the
+ // named one, and writing the blank would drop the metric from the link.
+ // A lone unnamed clause still writes its filters, as the single-series
+ // viewer always did.
+ const clause =
+ values.namedClauses[0] ?? (values.viewerClauses.length === 1 ? values.viewerClauses[0] : null)
+ updateSearchParams(params, 'metricName', clause?.metricName.trim() ?? '', '')
+ updateSearchParams(params, 'metricType', clause?.selectedMetricType ?? null, null)
+ if (clause?.metricName.trim()) {
+ // Never dropped while a metric is picked: 'sum' is both the default and a
+ // valid explicit choice, so a link that omitted it would restore with the
+ // metric type's recommended aggregation instead of the one on screen.
+ params.aggregation = clause.aggregation
+ } else {
+ delete params.aggregation
+ }
+ updateSearchParams(params, 'groupBy', clause?.groupByKeys ?? [], [] as string[])
+ updateSearchParams(
+ params,
+ 'filterGroup',
+ clause?.filterGroup ?? DEFAULT_UNIVERSAL_GROUP_FILTER,
+ DEFAULT_UNIVERSAL_GROUP_FILTER
+ )
}
updateSearchParams(params, 'dateFrom', values.dateFrom, DEFAULT_DATE_FROM)
updateSearchParams(params, 'dateTo', values.dateTo, null)
- updateSearchParams(params, 'groupBy', values.groupByKeys, [] as string[])
- updateSearchParams(params, 'filterGroup', values.filterGroup, DEFAULT_UNIVERSAL_GROUP_FILTER)
return params
})
queueMicrotask(() => {
@@ -263,6 +425,11 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([
setDateTo: () => syncUrl(),
setGroupByKeys: () => syncUrl(),
setFilterGroup: () => syncUrl(),
+ setClauses: () => syncUrl(),
+ setFormula: () => syncUrl(),
+ removeClause: () => syncUrl(),
+ duplicateClause: () => syncUrl(),
+ backfillClauses: () => syncUrl(),
}
}),
])
diff --git a/products/metrics/frontend/nodes/MetricsQueryNode.tsx b/products/metrics/frontend/nodes/MetricsQueryNode.tsx
index c45df347e087..1a9d2c37f4c5 100644
--- a/products/metrics/frontend/nodes/MetricsQueryNode.tsx
+++ b/products/metrics/frontend/nodes/MetricsQueryNode.tsx
@@ -47,7 +47,9 @@ export function MetricsQueryNode(props: {
const { response, responseLoading } = useValues(logic)
const series = seriesFromMetricsResponse(response)
const hasPoints = series.some((s) => s.points.length > 0)
- const fallbackName = props.query.clauses[0]?.metricName ?? 'metric'
+ // A formula query returns only the formula result (metricName is null on it),
+ // so the formula text itself is the honest name for an unlabelled series.
+ const fallbackName = props.query.formula ?? props.query.clauses[0]?.metricName ?? 'metric'
return (
<div className="relative flex flex-col w-full h-full min-h-[200px]">