:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): remove dashboard label filters, keep metric variables (#122658)
Frank Hamand9b814a81c9db
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 28953c10efd7..9c40085715d7 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -104,7 +104,6 @@ export type DashboardFilterChangeType =| 'interval'| 'test_accounts'| 'compare'- | 'metric_labels'| 'metric_variables'export enum InsightEventSource {diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 4fdc62c3064e..2b8fbede6766 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -18677,7 +18677,7 @@"type": "null"}],- "description": "Metric label matchers ANDed into every metrics tile. Other tiles ignore them."+ "deprecated": "Ignored. Kept so that dashboards saved with label filters still load."},"metricVariables": {"anyOf": [diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex aecafd698ab3..27906525ae17 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -6856,7 +6856,7 @@ export interface DashboardFilter {filterTestAccounts?: boolean | null/** Period comparison forced onto every insight that supports one. Absent/null = inherit. */compareFilter?: CompareFilter | null- /** Metric label matchers ANDed into every metrics tile. Other tiles ignore them. */+ /** @deprecated Ignored. Kept so that dashboards saved with label filters still load. */metricFilters?: MetricsQueryFilter[] | null/** Variables that metrics tiles refer to as `$name`. Other tiles ignore them. */metricVariables?: MetricsDashboardVariable[] | nulldiff --git a/frontend/src/scenes/dashboard/DashboardEditBar.tsx b/frontend/src/scenes/dashboard/DashboardEditBar.tsxindex 084f7e33e89b..e21d4aee5433 100644--- a/frontend/src/scenes/dashboard/DashboardEditBar.tsx+++ b/frontend/src/scenes/dashboard/DashboardEditBar.tsx@@ -29,7 +29,6 @@ import { VariablesForDashboard } from '~/queries/nodes/DataVisualization/Componeimport { BreakdownFilter, NodeKind } from '~/queries/schema/schema-general'import { InsightLogicProps, IntervalType } from '~/types'-import { DashboardMetricLabelFilter } from 'products/metrics/frontend/components/DashboardMetricLabelFilter'import { DashboardMetricVariables } from 'products/metrics/frontend/components/dashboardVariables/DashboardMetricVariables'interface DashboardEditBarProps {@@ -98,8 +97,7 @@ export function DashboardIntervalFilter(): JSX.Element {export function DashboardEditBar({ showDateFilter = true, className }: DashboardEditBarProps): JSX.Element {const { dashboard, dashboardEditing, hasVariables, effectiveEditBarFilters } = useValues(dashboardLogic)- const { setDates, setProperties, setBreakdownFilter, setMetricFilters, setDashboardEditing } =- useActions(dashboardLogic)+ const { setDates, setProperties, setBreakdownFilter, setDashboardEditing } = useActions(dashboardLogic)const controlsEnabled = useFeatureFlag('METRICS_DASHBOARD_CONTROLS')const { groupsTaxonomicTypes } = useValues(groupsModel)@@ -247,28 +245,6 @@ export function DashboardEditBar({ showDateFilter = true, className }: Dashboard<div className={clsx('content-end', { 'h-[61px]': hasVariables })}><DashboardEditBarAdvancedFilters showCompareFilter={showDateFilter} /></div>- {controlsEnabled && (- <DashboardControlSlot- control="metricLabels"- hasValue={(effectiveEditBarFilters.metricFilters?.length ?? 0) > 0}- className={clsx('content-end', { 'h-[61px]': hasVariables })}- >- <div className="flex min-h-[30px] flex-wrap items-center gap-1 border-l border-primary pl-2">- <DashboardMetricLabelFilter- metricFilters={effectiveEditBarFilters.metricFilters}- onChange={(metricFilters) => {- if (!dashboardEditing?.filters) {- setDashboardEditing(- { filters: true, layout: false },- DashboardEventSource.DashboardFilters- )- }- setMetricFilters(metricFilters)- }}- />- </div>- </DashboardControlSlot>- )}{controlsEnabled && (<DashboardControlSlotcontrol="metricVariables"diff --git a/frontend/src/scenes/dashboard/DashboardFilters.test.tsx b/frontend/src/scenes/dashboard/DashboardFilters.test.tsxindex 306282f8dddb..f893b1d31ee3 100644--- a/frontend/src/scenes/dashboard/DashboardFilters.test.tsx+++ b/frontend/src/scenes/dashboard/DashboardFilters.test.tsx@@ -62,5 +62,6 @@ describe('DashboardFilterBar', () => {expect(screen.getByText('Service')).toBeInTheDocument()expect(!!document.querySelector('[data-attr="dashboard-metric-variables-edit"]')).toBe(editable)+ expect(!!document.querySelector('[data-attr="dashboard-metric-variables-add"]')).toBe(editable)})})diff --git a/frontend/src/scenes/dashboard/dashboardControls.test.ts b/frontend/src/scenes/dashboard/dashboardControls.test.tsindex f0eb97364d85..c10d00fa4bed 100644--- a/frontend/src/scenes/dashboard/dashboardControls.test.ts+++ b/frontend/src/scenes/dashboard/dashboardControls.test.ts@@ -18,12 +18,7 @@ describe('dashboardControls', () => {it.each([['a trends insight', trendsTile, ['dateRange', 'interval', 'properties', 'breakdown', 'testAccounts']],['a retention insight', retentionTile, ['dateRange', 'properties', 'breakdown', 'testAccounts']],- ['a metrics insight', metricsTile, ['dateRange', 'metricLabels', 'metricVariables']],- [- 'a PromQL metrics insight',- insightTile({ kind: NodeKind.MetricsQuery, clauses: [], language: 'promql', promql: 'sum(x)' }),- ['dateRange', 'metricVariables'],- ],+ ['a metrics insight', metricsTile, ['dateRange', 'metricVariables']],['a SQL insight',insightTile({ kind: NodeKind.DataVisualizationNode, source: { kind: NodeKind.HogQLQuery, query: '' } }),@@ -39,7 +34,7 @@ describe('dashboardControls', () => {expect(scopes.dateRange).toEqual({ applies: 3, total: 3 })expect(scopes.interval).toEqual({ applies: 1, total: 3 })expect(scopes.properties).toEqual({ applies: 2, total: 3 })- expect(scopes.metricLabels).toEqual({ applies: 1, total: 3 })+ expect(scopes.metricVariables).toEqual({ applies: 1, total: 3 })})it.each([diff --git a/frontend/src/scenes/dashboard/dashboardControls.ts b/frontend/src/scenes/dashboard/dashboardControls.tsindex e72e0679e4cf..c7bb49ccc124 100644--- a/frontend/src/scenes/dashboard/dashboardControls.ts+++ b/frontend/src/scenes/dashboard/dashboardControls.ts@@ -1,4 +1,4 @@-import { MetricsQuery, Node, NodeKind } from '~/queries/schema/schema-general'+import { Node, NodeKind } from '~/queries/schema/schema-general'import { isNodeWithSource } from '~/queries/utils'import { DashboardTile } from '~/types'@@ -9,7 +9,6 @@ export type DashboardControl =| 'properties'| 'breakdown'| 'testAccounts'- | 'metricLabels'| 'metricVariables'export interface DashboardControlScope {@@ -25,7 +24,6 @@ const ALL_CONTROLS: DashboardControl[] = ['properties','breakdown','testAccounts',- 'metricLabels','metricVariables',]@@ -40,17 +38,12 @@ const CONTROLS_BY_QUERY_KIND: Partial<Record<NodeKind, DashboardControl[]>> = {[NodeKind.StickinessQuery]: ['dateRange', 'interval', 'properties', 'testAccounts'],[NodeKind.LifecycleQuery]: ['dateRange', 'interval', 'properties', 'testAccounts'],[NodeKind.CalendarHeatmapQuery]: ['dateRange', 'interval', 'properties', 'testAccounts'],- [NodeKind.MetricsQuery]: ['dateRange', 'metricLabels', 'metricVariables'],- [NodeKind.MetricsHistogramQuery]: ['dateRange', 'metricLabels', 'metricVariables'],+ [NodeKind.MetricsQuery]: ['dateRange', 'metricVariables'],+ [NodeKind.MetricsHistogramQuery]: ['dateRange', 'metricVariables'],}export function dashboardControlsForQuery(query: Node | null | undefined): DashboardControl[] {const source = isNodeWithSource(query) ? query.source : query- // Label filters reach builder clauses only, because PromQL and SQL text is not rewritten for them. Variables reach all three languages.- const metricsLanguage = source?.kind === NodeKind.MetricsQuery ? (source as MetricsQuery).language : undefined- if (metricsLanguage && metricsLanguage !== 'builder') {- return ['dateRange', 'metricVariables']- }return (source?.kind && CONTROLS_BY_QUERY_KIND[source.kind as NodeKind]) || DEFAULT_CONTROLS}diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex 376a27a930ab..7285555da00c 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -1202,7 +1202,6 @@ describe('dashboardLogic', () => {await expectLogic(logic, () => {logic.actions.setInterval('week')logic.actions.setFilterTestAccounts(true)- logic.actions.setMetricFilters([{ key: 'service.name', op: 'eq', value: 'checkout' }])}).toFinishAllListeners()expect(logic.values.dashboardSettingsDraft?.filters).toEqual(@@ -1212,7 +1211,6 @@ describe('dashboardLogic', () => {breakdown_filter: { breakdown: '$browser', breakdown_type: 'event' },interval: 'week',filterTestAccounts: true,- metricFilters: [{ key: 'service.name', op: 'eq', value: 'checkout' }],}))expect(logic.values.urlFilters).toEqual(@@ -1222,7 +1220,6 @@ describe('dashboardLogic', () => {breakdown_filter: { breakdown: '$browser', breakdown_type: 'event' },interval: 'week',filterTestAccounts: true,- metricFilters: [{ key: 'service.name', op: 'eq', value: 'checkout' }],}))diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex 178844d48fd1..29680787badd 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -92,7 +92,6 @@ import {DataVisualizationNode,HogQLVariable,MetricsDashboardVariable,- MetricsQueryFilter,NodeKind,RefreshType,} from '~/queries/schema/schema-general'@@ -1002,9 +1001,6 @@ export interface dashboardLogicActions {setLoadLayoutFromServerOnPreview: (loadLayoutFromServerOnPreview: boolean) => {loadLayoutFromServerOnPreview: boolean}- setMetricFilters: (metricFilters: MetricsQueryFilter[] | null) => {- metricFilters: MetricsQueryFilter[] | null- }setMetricVariables: (metricVariables: MetricsDashboardVariable[] | null) => {metricVariables: MetricsDashboardVariable[] | null}@@ -1586,7 +1582,6 @@ export const dashboardLogic = kea<dashboardLogicType>([setInterval: (interval: IntervalType | null) => ({ interval }),setFilterTestAccounts: (filterTestAccounts: boolean | null) => ({ filterTestAccounts }),setCompareFilter: (compareFilter: CompareFilter | null) => ({ compareFilter }),- setMetricFilters: (metricFilters: MetricsQueryFilter[] | null) => ({ metricFilters }),reportDashboardFilterChange: (changeType: DashboardFilterChangeType,properties: Record<string, string | number | boolean | null | undefined>@@ -2189,7 +2184,6 @@ export const dashboardLogic = kea<dashboardLogicType>([setInterval: () => false,setFilterTestAccounts: () => false,setCompareFilter: () => false,- setMetricFilters: () => false,setMetricVariables: () => false,overrideVariableValue: () => false,loadDashboardSuccess: () => false,@@ -5335,23 +5329,6 @@ export const dashboardLogic = kea<dashboardLogicType>([})}},- setMetricFilters: ({ metricFilters }) => {- actions.setDashboardSettingsDraft({- ...values.currentDashboardSettings,- filters: { ...values.currentDashboardSettings.filters, metricFilters },- })- actions.reportDashboardFilterChange('metric_labels', {- metric_filter_count: metricFilters?.length ?? 0,- })-- if (values.canAutoPreview) {- actions.refreshDashboardItems({- action: RefreshDashboardItemsAction.Preview,- forceRefresh: false,- previewUnsavedFilters: true,- })- }- },setMetricVariables: ({ metricVariables }) => {actions.setDashboardSettingsDraft({...values.currentDashboardSettings,@@ -5655,25 +5632,6 @@ export const dashboardLogic = kea<dashboardLogicType>([currentLocation.hashParams,]},- setMetricFilters: ({ metricFilters }) => {- const { currentLocation } = router.values-- const urlFilters = parseURLFilters(currentLocation.searchParams)- const newUrlFilters: DashboardFilter = {- ...urlFilters,- metricFilters,- }-- return [- currentLocation.pathname,- searchParamsWithUrlFilters(- currentLocation.searchParams,- newUrlFilters,- combineDashboardFilters(values.dashboard?.persisted_filters || {}, values.externalFilters)- ),- currentLocation.hashParams,- ]- },setMetricVariables: ({ metricVariables }) => {const { currentLocation } = router.valuesdiff --git a/posthog/schema.py b/posthog/schema.pyindex 6ddb31347536..4819666dde40 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -27535,10 +27535,7 @@ class DashboardFilter(BaseModel):default=None,description=("Time granularity forced onto every insight that supports one. Absent/null = inherit."),)- metricFilters: list[MetricsQueryFilter] | None = Field(- default=None,- description=("Metric label matchers ANDed into every metrics tile. Other tiles ignore them."),- )+ metricFilters: list[MetricsQueryFilter] | None = NonemetricVariables: list[MetricsDashboardVariable] | None = Field(default=None,description=("Variables that metrics tiles refer to as `$name`. Other tiles ignore them."),diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 928df43d0c55..4692d40103f3 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -2579,7 +2579,6 @@ export interface DashboardFilterApi {filterTestAccounts?: boolean | null/** Time granularity forced onto every insight that supports one. Absent/null = inherit. */interval?: IntervalTypeApi | null- /** Metric label matchers ANDed into every metrics tile. Other tiles ignore them. */metricFilters?: MetricsQueryFilterApi[] | null/** Variables that metrics tiles refer to as `$name`. Other tiles ignore them. */metricVariables?: MetricsDashboardVariableApi[] | nulldiff --git a/products/dashboards/frontend/dashboardSettings/dashboardChanges.ts b/products/dashboards/frontend/dashboardSettings/dashboardChanges.tsindex 5bc9bb338b3b..7c53a6583302 100644--- a/products/dashboards/frontend/dashboardSettings/dashboardChanges.ts+++ b/products/dashboards/frontend/dashboardSettings/dashboardChanges.ts@@ -322,17 +322,6 @@ export function getDashboardFilterChanges(})}- if (!dashboardFilterValuesEqual(previousFilters.metricFilters, currentFilters.metricFilters)) {- const previousLabels = formatMetricFilters(previousFilters)- const currentLabels = formatMetricFilters(currentFilters)- changes.push({- label: 'Metric labels',- previousValue: previousLabels,- value: currentLabels,- status: getChangeStatus(previousLabels.length > 0, currentLabels.length > 0),- })- }-if (!dashboardFilterValuesEqual(previousFilters.metricVariables, currentFilters.metricVariables)) {const previousLabels = formatMetricVariables(previousFilters)const currentLabels = formatMetricVariables(currentFilters)@@ -347,19 +336,6 @@ export function getDashboardFilterChanges(return changes}-const METRIC_FILTER_OP_LABELS: Record<NonNullable<DashboardFilter['metricFilters']>[number]['op'], string> = {- eq: '=',- neq: '!=',- regex: '=~',- not_regex: '!~',-}--function formatMetricFilters(filters: DashboardFilter): string[] {- return (filters.metricFilters ?? []).map(- (filter) => `${filter.key} ${METRIC_FILTER_OP_LABELS[filter.op]} ${filter.value}`- )-}-function formatMetricVariables(filters: DashboardFilter): string[] {return (filters.metricVariables ?? []).map((variable) => {const value = variable.current?.all ? 'All' : (variable.current?.values ?? []).join(', ')diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 0f409d3d083d..680ff264833c 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -9544,7 +9544,6 @@ export interface DashboardFilterApi {filterTestAccounts?: boolean | null/** Time granularity forced onto every insight that supports one. Absent/null = inherit. */interval?: IntervalTypeApi | null- /** Metric label matchers ANDed into every metrics tile. Other tiles ignore them. */metricFilters?: MetricsQueryFilterApi[] | null/** Variables that metrics tiles refer to as `$name`. Other tiles ignore them. */metricVariables?: MetricsDashboardVariableApi[] | nulldiff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.tsindex 729e9d054ae9..9197092a5c26 100644--- a/products/endpoints/frontend/generated/api.schemas.ts+++ b/products/endpoints/frontend/generated/api.schemas.ts@@ -1052,7 +1052,6 @@ export interface DashboardFilterApi {filterTestAccounts?: boolean | null/** Time granularity forced onto every insight that supports one. Absent/null = inherit. */interval?: IntervalTypeApi | null- /** Metric label matchers ANDed into every metrics tile. Other tiles ignore them. */metricFilters?: MetricsQueryFilterApi[] | null/** Variables that metrics tiles refer to as `$name`. Other tiles ignore them. */metricVariables?: MetricsDashboardVariableApi[] | nulldiff --git a/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py b/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.pyindex c749d8227cbb..a326a044dc31 100644--- a/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py+++ b/products/metrics/backend/hogql_queries/metrics_histogram_query_runner.py@@ -221,8 +221,6 @@ class MetricsHistogramQueryRunner(AnalyticsQueryRunner[MetricsHistogramQueryRespdate_from=dashboard_filter.date_from,date_to=dashboard_filter.date_to,)- if dashboard_filter.metricFilters:- self.query.filters = [*(self.query.filters or []), *dashboard_filter.metricFilters]if dashboard_filter.metricVariables:# The values go into the query, so each selection has its own cache entry and reaches the async worker.self.query.variables = (diff --git a/products/metrics/backend/hogql_queries/metrics_query_runner.py b/products/metrics/backend/hogql_queries/metrics_query_runner.pyindex fa79a35f859e..cd271a85355e 100644--- a/products/metrics/backend/hogql_queries/metrics_query_runner.py+++ b/products/metrics/backend/hogql_queries/metrics_query_runner.py@@ -273,19 +273,12 @@ class MetricsQueryRunner(AnalyticsQueryRunner[MetricsQueryResponse]):def apply_dashboard_filters(self, dashboard_filter: DashboardFilter) -> None:# Metric label predicates are not PostHog property filters, so the dashboard's- # property filters do not apply. Its date range, variables and label filters do.- # Variables reach all three languages. Label filters reach builder clauses only:- # PromQL and SQL text is not rewritten for them.+ # property filters do not apply. Its date range and variables do, in all three languages.if dashboard_filter.date_from or dashboard_filter.date_to:self.query.dateRange = DateRange(date_from=dashboard_filter.date_from,date_to=dashboard_filter.date_to,)- if dashboard_filter.metricFilters:- self.query.clauses = [- clause.model_copy(update={"filters": [*(clause.filters or []), *dashboard_filter.metricFilters]})- for clause in self.query.clauses- ]if dashboard_filter.metricVariables:self._apply_variables(dashboard_filter)diff --git a/products/metrics/backend/tests/test_metrics_histogram_query_runner.py b/products/metrics/backend/tests/test_metrics_histogram_query_runner.pyindex c4e5f3653936..db63b64a49a7 100644--- a/products/metrics/backend/tests/test_metrics_histogram_query_runner.py+++ b/products/metrics/backend/tests/test_metrics_histogram_query_runner.py@@ -64,7 +64,7 @@ class TestMetricsHistogramQueryRunner(ClickhouseTestMixin, APIBaseTest):)return MetricsHistogramQueryRunner(query=query, team=self.team).calculate()- def test_dashboard_metric_filters_add_to_the_query_filters(self):+ def test_dashboard_variables_apply_and_saved_metric_filters_do_not(self):own_filter = MetricsQueryFilter(key="namespace", op="eq", value="posthog")dashboard_filter = MetricsQueryFilter(key="service.name", op="eq", value="checkout")runner = MetricsHistogramQueryRunner(@@ -82,7 +82,7 @@ class TestMetricsHistogramQueryRunner(ClickhouseTestMixin, APIBaseTest):))- self.assertEqual(runner.query.filters, [own_filter, dashboard_filter])+ self.assertEqual(runner.query.filters, [own_filter])assert runner.query.variables is not None and runner.query.variables["window"].values == ["1m"]@parameterized.expand([("fixed", "minute"), ("variable", "$window")])diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.pyindex 91df9a69b2d4..66637b8e1611 100644--- a/products/metrics/backend/tests/test_metrics_query_runner.py+++ b/products/metrics/backend/tests/test_metrics_query_runner.py@@ -86,29 +86,6 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert request.interval == "minute"assert (request.date_to - request.date_from) == dt.timedelta(hours=1)- @time_machine.travel("2026-09-19T12:00:00Z", tick=False)- def test_dashboard_label_filters_can_use_dashboard_variables(self) -> None:- runner = MetricsQueryRunner(- query=MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")]),- team=self.team,- )-- runner.apply_dashboard_filters(- DashboardFilter(- metricFilters=[MetricsQueryFilter(key="job", op="eq", value="$job")],- metricVariables=[- MetricsDashboardVariable(- name="job",- source="custom",- customValues=["api"],- current=MetricsDashboardVariableSelection(values=["api"]),- )- ],- )- )-- assert runner.query.variables is not None and runner.query.variables["job"].values == ["api"]-def test_sql_tiles_check_the_budget_and_load_all_options_before_taking_a_concurrency_slot(self) -> None:events: list[str] = []@@ -333,7 +310,7 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert runner.query.dateRange.date_from == "-7d"assert runner.query.dateRange.date_to == "-1d"- def test_dashboard_metric_filters_apply_to_every_clause(self) -> None:+ def test_saved_dashboard_metric_filters_do_not_apply(self) -> None:own_filter = MetricsQueryFilter(key="namespace", op="eq", value="posthog")query = MetricsQuery(clauses=[@@ -346,8 +323,8 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):runner.apply_dashboard_filters(DashboardFilter(metricFilters=[dashboard_filter]))- assert runner.query.clauses[0].filters == [own_filter, dashboard_filter]- assert runner.query.clauses[1].filters == [dashboard_filter]+ assert runner.query.clauses[0].filters == [own_filter]+ assert runner.query.clauses[1].filters is Nonedef test_dashboard_property_filters_do_not_apply(self) -> None:query = MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="queue_depth", aggregation="sum")])diff --git a/products/metrics/frontend/components/DashboardMetricLabelFilter.tsx b/products/metrics/frontend/components/DashboardMetricLabelFilter.tsxdeleted file mode 100644index 4e81f7588653..000000000000--- a/products/metrics/frontend/components/DashboardMetricLabelFilter.tsx+++ /dev/null@@ -1,60 +0,0 @@-import { useEffect, useState } from 'react'--import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'-import { objectsEqual } from 'lib/utils/objects'--import type { MetricsQueryFilter } from '~/queries/schema/schema-general'-import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'--import { MetricsClauseFilterBar } from './MetricsClauseFilterBar'-import { filterGroupFromMetricFilters, metricFiltersForGroup } from './metricsViewerLogic'--const toMetricFilters = (group: UniversalFiltersGroup): MetricsQueryFilter[] =>- metricFiltersForGroup(group) as MetricsQueryFilter[]--/** Dashboard-level metric label matchers, such as `service.name = checkout`, that every metrics tile applies. */-export function DashboardMetricLabelFilter({- metricFilters,- onChange,- disabledReason = null,-}: {- metricFilters: MetricsQueryFilter[] | null | undefined- onChange: (metricFilters: MetricsQueryFilter[] | null) => void- disabledReason?: string | null-}): JSX.Element {- // A chip that is still being edited has no matcher yet, so the chips are kept here- // and only complete matchers go to the dashboard filters.- const [filterGroup, setFilterGroup] = useState(() => filterGroupFromMetricFilters(metricFilters ?? []))-- useEffect(() => {- if (!objectsEqual(toMetricFilters(filterGroup), metricFilters ?? [])) {- setFilterGroup(filterGroupFromMetricFilters(metricFilters ?? []))- }- }, [metricFilters]) // eslint-disable-line react-hooks/exhaustive-deps-- return (- <UniversalFilters- rootKey="dashboard-metric-label-filters"- group={filterGroup.values[0] as UniversalFiltersGroup}- taxonomicGroupTypes={[TaxonomicFilterGroupType.MetricAttributes]}- onChange={(group) => {- if (disabledReason) {- return- }- const nextGroup: UniversalFiltersGroup = { type: FilterLogicalOperator.And, values: [group] }- setFilterGroup(nextGroup)- const nextFilters = toMetricFilters(nextGroup)- if (!objectsEqual(nextFilters, metricFilters ?? [])) {- onChange(nextFilters.length ? nextFilters : null)- }- }}- >- <MetricsClauseFilterBar- disabledReason={disabledReason}- addFilterTitle="Metrics Filter"- addFilterType="tertiary"- />- </UniversalFilters>- )-}diff --git a/products/metrics/frontend/components/dashboardVariables/DashboardMetricVariables.tsx b/products/metrics/frontend/components/dashboardVariables/DashboardMetricVariables.tsxindex a38aac72fe46..159d2774af9d 100644--- a/products/metrics/frontend/components/dashboardVariables/DashboardMetricVariables.tsx+++ b/products/metrics/frontend/components/dashboardVariables/DashboardMetricVariables.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { useMemo, useState } from 'react'-import { IconGear } from '@posthog/icons'+import { IconGear, IconPlusSmall } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import { DashboardEventSource } from 'lib/utils/eventUsageLogic'@@ -16,10 +16,12 @@ import { MetricVariablesModal } from './MetricVariablesModal'const NO_VARIABLES: MetricsDashboardVariable[] = []+type EditorMode = 'edit' | 'add'+export function DashboardMetricVariables({ editable = true }: { editable?: boolean }): JSX.Element | null {const { dashboard, dashboardEditing, effectiveEditBarFilters } = useValues(dashboardLogic)const { setMetricVariables, setDashboardEditing } = useActions(dashboardLogic)- const [editorOpen, setEditorOpen] = useState(false)+ const [editorMode, setEditorMode] = useState<EditorMode | null>(null)const metricVariables = effectiveEditBarFilters.metricVariables// A name from the URL without a saved definition, such as a deleted variable, has nothing to show.@@ -62,28 +64,38 @@ export function DashboardMetricVariables({ editable = true }: { editable?: booleonChange={(current) => select(variable.name, current)}/>))}- {editable && (+ {editable && shown.length > 0 && (<LemonButtonsize="small"type="tertiary"icon={<IconGear />}- tooltip={shown.length ? 'Edit variables' : undefined}- onClick={() => setEditorOpen(true)}+ tooltip="Edit variables"+ onClick={() => setEditorMode('edit')}data-attr="dashboard-metric-variables-edit"+ />+ )}+ {editable && (+ <LemonButton+ size="small"+ type="tertiary"+ icon={<IconPlusSmall />}+ onClick={() => setEditorMode('add')}+ data-attr="dashboard-metric-variables-add">- {shown.length ? null : 'Add variable'}+ Add variable</LemonButton>)}- {editorOpen && (+ {editorMode && (<MetricVariablesModaldashboardId={dashboard.id}variables={shown}options={options}dateFrom={effectiveEditBarFilters.date_from}dateTo={effectiveEditBarFilters.date_to}- onClose={() => setEditorOpen(false)}+ addVariableOnOpen={editorMode === 'add'}+ onClose={() => setEditorMode(null)}onSave={(next) => {- setEditorOpen(false)+ setEditorMode(null)stage(next, variablesToReload(shown, next))}}/>diff --git a/products/metrics/frontend/components/dashboardVariables/MetricVariablesModal.tsx b/products/metrics/frontend/components/dashboardVariables/MetricVariablesModal.tsxindex da36dc657abe..0cb897ecbec4 100644--- a/products/metrics/frontend/components/dashboardVariables/MetricVariablesModal.tsx+++ b/products/metrics/frontend/components/dashboardVariables/MetricVariablesModal.tsx@@ -22,6 +22,7 @@ export function MetricVariablesModal({options,dateFrom,dateTo,+ addVariableOnOpen = false,onClose,onSave,}: {@@ -30,15 +31,20 @@ export function MetricVariablesModal({options: Record<string, string[]>dateFrom?: string | nulldateTo?: string | null+ /** Opens on a new, empty variable instead of the first saved one. */+ addVariableOnOpen?: booleanonClose: () => voidonSave: (variables: MetricsDashboardVariable[]) => void}): JSX.Element {- const logic = metricVariableEditorLogic({ dashboardId, variables, options, dateFrom, dateTo })+ const logic = metricVariableEditorLogic({ dashboardId, variables, options, dateFrom, dateTo, addVariableOnOpen })const { applying, draft, selectedIndex, selectedVariable, shownErrors } = useValues(logic)const { addVariable, selectVariable, apply } = useActions(logic)return (- <BindLogic logic={metricVariableEditorLogic} props={{ dashboardId, variables, options, dateFrom, dateTo }}>+ <BindLogic+ logic={metricVariableEditorLogic}+ props={{ dashboardId, variables, options, dateFrom, dateTo, addVariableOnOpen }}+ ><LemonModalisOpenonClose={onClose}diff --git a/products/metrics/frontend/components/dashboardVariables/metricVariableEditorLogic.test.ts b/products/metrics/frontend/components/dashboardVariables/metricVariableEditorLogic.test.tsindex 584cf7c9ce09..a7a0cb02267f 100644--- a/products/metrics/frontend/components/dashboardVariables/metricVariableEditorLogic.test.ts+++ b/products/metrics/frontend/components/dashboardVariables/metricVariableEditorLogic.test.ts@@ -19,6 +19,21 @@ describe('metricVariableEditorLogic', () => {initKeaTests()})+ it('opens on one new variable after the saved ones when it adds a variable on open', async () => {+ mockOptions.mockResolvedValue({ results: [] })+ const logic = metricVariableEditorLogic({+ dashboardId: 1,+ variables: [{ name: 'job', source: 'custom', customValues: ['a'] }],+ options: {},+ addVariableOnOpen: true,+ })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.draft.map((variable) => variable.name)).toEqual(['job', expect.any(String)])+ expect(logic.values.selectedIndex).toBe(1)+ })+it('previews a query edit after an edit to another field', async () => {mockOptions.mockResolvedValue({ results: ['a'] })const logic = metricVariableEditorLogic({diff --git a/products/metrics/frontend/components/dashboardVariables/metricVariableEditorLogic.ts b/products/metrics/frontend/components/dashboardVariables/metricVariableEditorLogic.tsindex 44c424d8e730..bbef47dd95ca 100644--- a/products/metrics/frontend/components/dashboardVariables/metricVariableEditorLogic.ts+++ b/products/metrics/frontend/components/dashboardVariables/metricVariableEditorLogic.ts@@ -31,6 +31,8 @@ export interface MetricVariableEditorLogicProps {/** The dashboard date filter, so the preview shows the values of the dashboard window. */dateFrom?: string | nulldateTo?: string | null+ /** Opens on a new, empty variable instead of the first saved one. */+ addVariableOnOpen?: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -139,6 +141,10 @@ export type metricVariableEditorLogicType = MakeLogicType<metricVariableEditorLogicMeta>+function newVariable(variables: MetricsDashboardVariable[]): MetricsDashboardVariable {+ return { name: newVariableName(variables), source: 'custom', customValues: [] } as MetricsDashboardVariable+}+function withSourceSettings(variable: MetricsDashboardVariable, previousSource: string): MetricsDashboardVariable {if (variable.source === previousSource || variable.source === 'promql' || variable.source === 'sql') {return variable@@ -278,12 +284,9 @@ export const metricVariableEditorLogic = kea<metricVariableEditorLogicType>([}),reducers(({ props }) => ({draft: [- props.variables,+ props.addVariableOnOpen ? [...props.variables, newVariable(props.variables)] : props.variables,{- addVariable: (state) => [- ...state,- { name: newVariableName(state), source: 'custom', customValues: [] } as MetricsDashboardVariable,- ],+ addVariable: (state) => [...state, newVariable(state)],removeVariable: (state, { index }) => state.filter((_, other) => other !== index),moveVariable: (state, { index, offset }) => {const target = index + offset@@ -301,7 +304,7 @@ export const metricVariableEditorLogic = kea<metricVariableEditorLogicType>([},],selectedIndex: [- 0,+ props.addVariableOnOpen ? props.variables.length : 0,{selectVariable: (_, { index }) => index,removeVariable: (state, { index }) => (state >= index ? Math.max(state - 1, 0) : state),diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex a252e090a59b..dbee4de9ca81 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -8660,7 +8660,6 @@ export interface DashboardFilterApi {filterTestAccounts?: boolean | null/** Time granularity forced onto every insight that supports one. Absent/null = inherit. */interval?: IntervalTypeApi | null- /** Metric label matchers ANDed into every metrics tile. Other tiles ignore them. */metricFilters?: MetricsQueryFilterApi[] | null/** Variables that metrics tiles refer to as `$name`. Other tiles ignore them. */metricVariables?: MetricsDashboardVariableApi[] | nulldiff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 5cf1e06ec9a9..a6e83fd63e29 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -772,7 +772,7 @@]},"filters_override": {- "description": "Object (or pre-encoded JSON string) to override the insight's filters for this run only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepted keys: `date_from`, `date_to`, `explicitDate`, `interval`, `properties`, `filterTestAccounts`, `breakdown_filter`, `compareFilter`, `metricFilters`, `metricVariables`. Other keys (for example `display`, `dateRange`, `filter_test_accounts` or `compare`) are rejected. Ignored when accessed via a sharing token.",+ "description": "Object (or pre-encoded JSON string) to override the insight's filters for this run only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepted keys: `date_from`, `date_to`, `explicitDate`, `interval`, `properties`, `filterTestAccounts`, `breakdown_filter`, `compareFilter`, `metricVariables`. Other keys (for example `display`, `dateRange`, `filter_test_accounts` or `compare`) are rejected. Ignored when accessed via a sharing token.","anyOf": [{"type": "string"diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e48dd75a146a..5049f5902508 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -3802,7 +3802,6 @@ export namespace Schemas {filterTestAccounts?: boolean | null;/** Time granularity forced onto every insight that supports one. Absent/null = inherit. */interval?: IntervalType | null;- /** Metric label matchers ANDed into every metrics tile. Other tiles ignore them. */metricFilters?: MetricsQueryFilter[] | null;/** Variables that metrics tiles refer to as `$name`. Other tiles ignore them. */metricVariables?: MetricsDashboardVariable[] | null;diff --git a/services/mcp/src/generated/endpoints/api.ts b/services/mcp/src/generated/endpoints/api.tsindex 1870f9137db8..f52c3c60db6e 100644--- a/services/mcp/src/generated/endpoints/api.ts+++ b/services/mcp/src/generated/endpoints/api.ts@@ -473,8 +473,7 @@ export const EndpointsRunCreateBody = () => zod.object({),zod.null(),])- .optional()- .describe('Metric label matchers ANDed into every metrics tile. Other tiles ignore them.'),+ .optional(),metricVariables: zod.union([zod.array(diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 0ee0b318f93d..18bfd3f6fa38 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -552,7 +552,7 @@ export const InsightQueryInputSchema = z.preprocess(.union([z.string(), z.record(z.string(), z.unknown())]).optional().describe(- "Object (or pre-encoded JSON string) to override the insight's filters for this run only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepted keys: `date_from`, `date_to`, `explicitDate`, `interval`, `properties`, `filterTestAccounts`, `breakdown_filter`, `compareFilter`, `metricFilters`, `metricVariables`. Other keys (for example `display`, `dateRange`, `filter_test_accounts` or `compare`) are rejected. Ignored when accessed via a sharing token."+ "Object (or pre-encoded JSON string) to override the insight's filters for this run only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepted keys: `date_from`, `date_to`, `explicitDate`, `interval`, `properties`, `filterTestAccounts`, `breakdown_filter`, `compareFilter`, `metricVariables`. Other keys (for example `display`, `dateRange`, `filter_test_accounts` or `compare`) are rejected. Ignored when accessed via a sharing token."),}))diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-query.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-query.jsonindex 4342a312d480..c4bc0b29f136 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-query.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insight-query.json@@ -14,7 +14,7 @@"type": "object"}],- "description": "Object (or pre-encoded JSON string) to override the insight's filters for this run only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepted keys: `date_from`, `date_to`, `explicitDate`, `interval`, `properties`, `filterTestAccounts`, `breakdown_filter`, `compareFilter`, `metricFilters`, `metricVariables`. Other keys (for example `display`, `dateRange`, `filter_test_accounts` or `compare`) are rejected. Ignored when accessed via a sharing token."+ "description": "Object (or pre-encoded JSON string) to override the insight's filters for this run only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepted keys: `date_from`, `date_to`, `explicitDate`, `interval`, `properties`, `filterTestAccounts`, `breakdown_filter`, `compareFilter`, `metricVariables`. Other keys (for example `display`, `dateRange`, `filter_test_accounts` or `compare`) are rejected. Ignored when accessed via a sharing token."},"insightId": {"anyOf": [