Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

fix: remove widget filter references when a dashboard variable is deleted (#11270)

Rinky Devi86e71151d796
diff --git a/frontend/src/components/QueryBuilderV2/utils.ts b/frontend/src/components/QueryBuilderV2/utils.ts
index 0ce347391b..67b21dd510 100644
--- a/frontend/src/components/QueryBuilderV2/utils.ts
+++ b/frontend/src/components/QueryBuilderV2/utils.ts
@@ -721,6 +721,53 @@ export const removeKeysFromExpression = (
return result?.text ?? '';
};
+const escapeRegExp = (value: string): string =>
+ value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+export const createVariablePlaceholderRegExp = (
+ variableName: string,
+): RegExp => {
+ const escapedName = escapeRegExp(variableName);
+ // (?![\w.]) prevents $env from matching inside $environment or $env.attr
+ return new RegExp(
+ `(\\$${escapedName}(?![\\w.])|\\{\\{\\s*\\.?${escapedName}\\s*\\}\\}|\\[\\[\\s*${escapedName}\\s*\\]\\])`,
+ 'g',
+ );
+};
+
+const matchesVariablePlaceholder = (
+ text: string,
+ variableName: string,
+): boolean => createVariablePlaceholderRegExp(variableName).test(text);
+
+export const removeVariableFromExpression = (
+ expression: string | undefined,
+ variableName: string,
+): string => {
+ if (!expression) {
+ return '';
+ }
+
+ const queryPairs = extractQueryPairs(expression);
+
+ const keysToRemove = queryPairs
+ .filter((pair) => {
+ const singleValue = pair.value?.toString() ?? '';
+ const listValues = (pair.valueList ?? []).join(' ');
+ return (
+ matchesVariablePlaceholder(singleValue, variableName) ||
+ matchesVariablePlaceholder(listValues, variableName)
+ );
+ })
+ .map((pair) => pair.key);
+
+ if (keysToRemove.length === 0) {
+ return expression;
+ }
+
+ return removeKeysFromExpression(expression, keysToRemove, `$${variableName}`);
+};
+
/**
* Convert old having format to new having format
* @param having - Array of old having objects with columnName, op, and value
diff --git a/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/addTagFiltersToDashboard.test.tsx b/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/addTagFiltersToDashboard.test.tsx
new file mode 100644
index 0000000000..e4f0576f0b
--- /dev/null
+++ b/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/addTagFiltersToDashboard.test.tsx
@@ -0,0 +1,328 @@
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { Dashboard } from 'types/api/dashboard/getAll';
+import { EQueryType } from 'types/common/dashboard';
+import { DataSource } from 'types/common/queryBuilder';
+import { removeVariableReferencesFromDashboard } from './addTagFiltersToDashboard';
+
+// ---------------------------------------------------------------------------
+// Shared fixture helpers
+// ---------------------------------------------------------------------------
+
+const EMPTY_BUILDER = {
+ queryData: [] as any,
+ queryFormulas: [],
+ queryTraceOperator: [],
+};
+
+const BASE_WIDGET = {
+ opacity: '1',
+ nullZeroValues: 'null',
+ timePreferance: 'GLOBAL_TIME' as const,
+ softMin: null,
+ softMax: null,
+ selectedLogFields: null,
+ selectedTracesFields: null,
+};
+
+const DEFAULT_QUERY_DATA = {
+ queryName: 'q1',
+ // In QB v5, expression holds the query label (A/B/C), not a filter expression
+ expression: 'A',
+ dataSource: DataSource.METRICS,
+ functions: [],
+ groupBy: [],
+ filters: { items: [] as any[], op: 'AND' as const },
+ legend: '',
+ disabled: false,
+ having: [],
+ limit: null,
+ stepInterval: null,
+ orderBy: [],
+ selectColumns: [],
+ source: '' as const,
+};
+
+/**
+ * Build a dashboard with a single builder widget.
+ * Only supply the fields your test actually cares about.
+ */
+const buildBuilderDashboard = (
+ filterExpression: string,
+ queryDataOverrides: Record<string, any> = {},
+): Dashboard => ({
+ id: 'dash1',
+ createdAt: '',
+ updatedAt: '',
+ createdBy: '',
+ updatedBy: '',
+ data: {
+ title: 'Test Dashboard',
+ widgets: [
+ {
+ ...BASE_WIDGET,
+ id: 'widget-1',
+ panelTypes: PANEL_TYPES.TIME_SERIES,
+ title: 'Widget 1',
+ description: '',
+ query: {
+ id: 'query1',
+ queryType: EQueryType.QUERY_BUILDER,
+ promql: [],
+ clickhouse_sql: [],
+ builder: {
+ queryData: [
+ {
+ ...DEFAULT_QUERY_DATA,
+ ...queryDataOverrides,
+ filter: { expression: filterExpression },
+ },
+ ],
+ queryFormulas: [],
+ queryTraceOperator: [],
+ },
+ unit: '',
+ },
+ },
+ ],
+ variables: {},
+ },
+});
+
+const buildClickhouseDashboard = (query: string): Dashboard => ({
+ id: 'dash-ch',
+ createdAt: '',
+ updatedAt: '',
+ createdBy: '',
+ updatedBy: '',
+ data: {
+ title: 'CH',
+ widgets: [
+ {
+ ...BASE_WIDGET,
+ id: 'w1',
+ panelTypes: PANEL_TYPES.TIME_SERIES,
+ title: '',
+ description: '',
+ query: {
+ id: 'q1',
+ queryType: EQueryType.CLICKHOUSE,
+ promql: [],
+ clickhouse_sql: [{ name: 'A', query, legend: '', disabled: false }],
+ builder: EMPTY_BUILDER,
+ unit: '',
+ },
+ },
+ ],
+ variables: {},
+ },
+});
+
+const buildPromqlDashboard = (query: string): Dashboard => ({
+ id: 'dash-prom',
+ createdAt: '',
+ updatedAt: '',
+ createdBy: '',
+ updatedBy: '',
+ data: {
+ title: 'PromQL Dashboard',
+ widgets: [
+ {
+ ...BASE_WIDGET,
+ id: 'widget-prom',
+ panelTypes: PANEL_TYPES.TIME_SERIES,
+ title: 'PromQL Widget',
+ description: '',
+ query: {
+ id: 'query-prom',
+ queryType: EQueryType.PROM,
+ promql: [{ name: 'A', query, legend: '', disabled: false }],
+ clickhouse_sql: [],
+ builder: EMPTY_BUILDER,
+ unit: '',
+ },
+ },
+ ],
+ variables: {},
+ },
+});
+
+/** Run removeVariableReferencesFromDashboard on a single-widget clickhouse dashboard and return the cleaned SQL. */
+const chQuery = (sql: string, varName: string): string => {
+ const result = removeVariableReferencesFromDashboard(
+ buildClickhouseDashboard(sql),
+ varName,
+ );
+ return (result!.data.widgets![0] as any).query.clickhouse_sql[0].query;
+};
+
+/** Extract the first builder queryData from a cleaned dashboard. */
+const firstBuilderQueryData = (dashboard: Dashboard | undefined): any =>
+ (dashboard!.data.widgets![0] as any).query.builder.queryData[0];
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe('removeVariableReferencesFromDashboard', () => {
+ describe('builder filter expression cleanup', () => {
+ it('removes a variable clause from filter.expression', () => {
+ const dashboard = buildBuilderDashboard(
+ "service.name IN $service AND env = 'prod'",
+ );
+
+ const result = removeVariableReferencesFromDashboard(dashboard, 'service');
+
+ expect(firstBuilderQueryData(result).filter.expression).toBe("env = 'prod'");
+ });
+
+ it('leaves no dangling AND/OR after removing a variable clause', () => {
+ const dashboard = buildBuilderDashboard(
+ "service.name IN $service AND env = 'prod'",
+ );
+
+ const result = removeVariableReferencesFromDashboard(dashboard, 'service');
+ const { expression } = firstBuilderQueryData(result).filter;
+
+ expect(expression).toBe("env = 'prod'");
+ expect(expression).not.toMatch(/^\s*(AND|OR)/i);
+ expect(expression).not.toMatch(/(AND|OR)\s*$/i);
+ });
+
+ it('does not remove $environment clause when deleting $env', () => {
+ const dashboard = buildBuilderDashboard(
+ 'env = $env AND deployment.environment = $environment',
+ );
+
+ const result = removeVariableReferencesFromDashboard(dashboard, 'env');
+
+ expect(firstBuilderQueryData(result).filter.expression).toBe(
+ 'deployment.environment = $environment',
+ );
+ });
+
+ it('leaves literal filter expressions untouched when removing a variable', () => {
+ const dashboard = buildBuilderDashboard(
+ "service.name = 'api-gateway' AND env = 'prod'",
+ );
+
+ const result = removeVariableReferencesFromDashboard(dashboard, 'service');
+
+ expect(firstBuilderQueryData(result).filter.expression).toBe(
+ "service.name = 'api-gateway' AND env = 'prod'",
+ );
+ });
+
+ it('removes only the variable clause, preserving a literal clause on the same key', () => {
+ const dashboard = buildBuilderDashboard(
+ "service.name IN $service AND service.name = 'api-gateway'",
+ );
+
+ const result = removeVariableReferencesFromDashboard(dashboard, 'service');
+
+ expect(firstBuilderQueryData(result).filter.expression).toBe(
+ "service.name = 'api-gateway'",
+ );
+ });
+
+ it('returns filter.expression unchanged when the variable has no clauses in it', () => {
+ const dashboard = buildBuilderDashboard("env = 'prod'");
+
+ const result = removeVariableReferencesFromDashboard(dashboard, 'service');
+
+ expect(firstBuilderQueryData(result).filter.expression).toBe("env = 'prod'");
+ });
+ });
+
+ describe('PromQL query cleanup', () => {
+ it('removes variable placeholder from a promql query', () => {
+ const result = removeVariableReferencesFromDashboard(
+ buildPromqlDashboard('sum(rate(http_requests_total{$service}[5m]))'),
+ 'service',
+ );
+
+ const widget = result!.data.widgets![0] as any;
+ expect(widget.query.promql[0].query).toBe(
+ 'sum(rate(http_requests_total{}[5m]))',
+ );
+ });
+
+ it('strips only the variable token inside a PromQL label matcher (token-only path)', () => {
+ const result = removeVariableReferencesFromDashboard(
+ buildPromqlDashboard('up{env="$env", job="api"}'),
+ 'env',
+ );
+
+ const widget = result!.data.widgets![0] as any;
+ expect(widget.query.promql[0].query).toBe('up{env="", job="api"}');
+ });
+ });
+
+ describe('ClickHouse SQL query cleanup', () => {
+ it('removes a quoted variable clause and its WHERE keyword', () => {
+ expect(
+ chQuery(
+ "SELECT count() FROM signoz_logs WHERE service_name = '$service'",
+ 'service',
+ ),
+ ).toBe('SELECT count() FROM signoz_logs');
+ });
+
+ it('removes a middle clause: AND env={{.env}} AND', () => {
+ expect(
+ chQuery('SELECT count() FROM t WHERE a=1 AND env={{.env}} AND b=2', 'env'),
+ ).toBe('SELECT count() FROM t WHERE a=1 AND b=2');
+ });
+
+ it('removes the first clause: env={{.env}} AND rest', () => {
+ expect(
+ chQuery('SELECT count() FROM t WHERE env={{.env}} AND b=2', 'env'),
+ ).toBe('SELECT count() FROM t WHERE b=2');
+ });
+
+ it('removes the last clause: rest AND env=$env', () => {
+ expect(chQuery('SELECT count() FROM t WHERE a=1 AND env=$env', 'env')).toBe(
+ 'SELECT count() FROM t WHERE a=1',
+ );
+ });
+
+ it('removes a clause with double-bracket syntax: service=[[svc]]', () => {
+ expect(chQuery('SELECT count() FROM t WHERE service=[[svc]]', 'svc')).toBe(
+ 'SELECT count() FROM t',
+ );
+ });
+
+ it('falls back to token-only strip for a bare variable in SELECT', () => {
+ expect(chQuery('SELECT $metric FROM table', 'metric')).toBe(
+ 'SELECT FROM table',
+ );
+ });
+ });
+
+ describe('edge cases', () => {
+ it('is idempotent — calling twice produces the same result', () => {
+ const dashboard = buildBuilderDashboard(
+ "service.name IN $service AND env = 'prod'",
+ );
+
+ const once = removeVariableReferencesFromDashboard(dashboard, 'service');
+ const twice = removeVariableReferencesFromDashboard(once, 'service');
+
+ expect(twice).toStrictEqual(once);
+ });
+
+ it('handles a dashboard with no widgets without throwing', () => {
+ const dashboard: Dashboard = {
+ id: 'dash-empty',
+ createdAt: '',
+ updatedAt: '',
+ createdBy: '',
+ updatedBy: '',
+ data: { title: 'Empty Dashboard', widgets: undefined, variables: {} },
+ };
+
+ expect(() =>
+ removeVariableReferencesFromDashboard(dashboard, 'service'),
+ ).not.toThrow();
+ });
+ });
+});
diff --git a/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/addTagFiltersToDashboard.tsx b/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/addTagFiltersToDashboard.tsx
index 4c3d93f407..6014480f71 100644
--- a/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/addTagFiltersToDashboard.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/addTagFiltersToDashboard.tsx
@@ -1,6 +1,8 @@
import {
convertFiltersToExpressionWithExistingQuery,
+ createVariablePlaceholderRegExp,
removeKeysFromExpression,
+ removeVariableFromExpression,
} from 'components/QueryBuilderV2/utils';
import { cloneDeep, isArray, isEmpty } from 'lodash-es';
import { Dashboard, Widgets } from 'types/api/dashboard/getAll';
@@ -157,6 +159,139 @@ const updateAfterRemoval = (
};
};
+const removeVariablePlaceholders = (
+ text: string | undefined,
+ variableName: string,
+): string => {
+ if (!text) {
+ return '';
+ }
+
+ const tokenPattern = createVariablePlaceholderRegExp(variableName);
+
+ // Step 1: attempt clause-aware removal for SQL WHERE patterns.
+ // Strips the entire `key op $var` unit plus its adjacent AND/OR so we
+ // never leave a dangling `key = ` in unquoted ClickHouse SQL clauses.
+ // Handles three shapes:
+ // (a) preceding conjunction: AND key = $var
+ // (b) following conjunction: key = $var AND
+ // (c) standalone clause: key = $var (end of expression)
+ const escapedToken = tokenPattern.source;
+ const clausePattern = new RegExp(
+ // (a) conjunction before the clause
+ `\\s*\\b(?:AND|OR)\\b\\s+[\\w."'\\[\\]]+\\s*(?:=|!=|<>|LIKE|ILIKE|IN|NOT\\s+IN)\\s*'?${escapedToken}'?` +
+ // (b)+(c) clause first, optional conjunction after
+ `|[\\w."'\\[\\]]+\\s*(?:=|!=|<>|LIKE|ILIKE|IN|NOT\\s+IN)\\s*'?${escapedToken}'?(?:\\s*\\b(?:AND|OR)\\b)?`,
+ 'gi',
+ );
+
+ const withClauseRemoval = text.replace(clausePattern, '');
+ if (withClauseRemoval !== text) {
+ return withClauseRemoval
+ .replace(/\s{2,}/g, ' ')
+ .replace(/\bWHERE\s*$/i, '')
+ .trim();
+ }
+
+ // Step 2: fallback — bare variable usage outside a key-op-value pattern
+ // (e.g. SELECT $metric, LIMIT $n). Token-only removal is correct here.
+ return text
+ .replace(tokenPattern, '')
+ .replace(/\s{2,}/g, ' ')
+ .trim();
+};
+
+const removeVariableReferencesFromQueryData = (
+ queryData: IBuilderQuery,
+ variableName: string,
+): IBuilderQuery => {
+ const updatedFilter = queryData.filter?.expression
+ ? {
+ ...queryData.filter,
+ expression: removeVariableFromExpression(
+ queryData.filter.expression,
+ variableName,
+ ),
+ }
+ : queryData.filter;
+
+ return { ...queryData, filter: updatedFilter };
+};
+
+const removeVariableReferencesFromWidget = (
+ widget: Widgets,
+ variableName: string,
+): Widgets => {
+ let updatedWidget = { ...widget };
+
+ if (updatedWidget.query?.builder?.queryData) {
+ updatedWidget = {
+ ...updatedWidget,
+ query: {
+ ...updatedWidget.query,
+ builder: {
+ ...updatedWidget.query.builder,
+ queryData: updatedWidget.query.builder.queryData.map((queryData) =>
+ removeVariableReferencesFromQueryData(queryData, variableName),
+ ),
+ },
+ },
+ };
+ }
+
+ if (updatedWidget.query?.promql) {
+ updatedWidget = {
+ ...updatedWidget,
+ query: {
+ ...updatedWidget.query,
+ promql: updatedWidget.query.promql.map((promqlQuery) => ({
+ ...promqlQuery,
+ query: removeVariablePlaceholders(promqlQuery.query, variableName),
+ })),
+ },
+ };
+ }
+
+ if (updatedWidget.query?.clickhouse_sql) {
+ updatedWidget = {
+ ...updatedWidget,
+ query: {
+ ...updatedWidget.query,
+ clickhouse_sql: updatedWidget.query.clickhouse_sql.map((sqlQuery) => ({
+ ...sqlQuery,
+ query: removeVariablePlaceholders(sqlQuery.query, variableName),
+ })),
+ },
+ };
+ }
+
+ return updatedWidget;
+};
+
+export const removeVariableReferencesFromDashboard = (
+ dashboard: Dashboard | undefined,
+ variableName: string,
+): Dashboard | undefined => {
+ if (!dashboard || !variableName) {
+ return dashboard;
+ }
+
+ const updatedDashboard = cloneDeep(dashboard);
+
+ if (updatedDashboard.data.widgets) {
+ updatedDashboard.data.widgets = updatedDashboard.data.widgets.map(
+ (widget) => {
+ if ('query' in widget) {
+ return removeVariableReferencesFromWidget(widget as Widgets, variableName);
+ }
+ return widget;
+ },
+ );
+ }
+
+ return updatedDashboard;
+};
+
/**
* A function that takes a dashboard configuration and a list of tag filters
* and returns an updated dashboard with the filters appended to widget queries.
diff --git a/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/index.tsx b/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/index.tsx
index c049c97813..f39e9955b4 100644
--- a/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/index.tsx
+++ b/frontend/src/container/DashboardContainer/DashboardSettings/DashboardVariableSettings/index.tsx
@@ -18,10 +18,11 @@ import { convertVariablesToDbFormat } from 'container/DashboardContainer/Dashboa
import { useAddDynamicVariableToPanels } from 'hooks/dashboard/useAddDynamicVariableToPanels';
import { useDashboardVariables } from 'hooks/dashboard/useDashboardVariables';
import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
-import { useNotifications } from 'hooks/useNotifications';
+import { toast } from '@signozhq/ui/sonner';
import { IDashboardVariables } from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStoreTypes';
import { useDashboardStore } from 'providers/Dashboard/store/useDashboardStore';
import { IDashboardVariable } from 'types/api/dashboard/getAll';
+import { removeVariableReferencesFromDashboard } from './addTagFiltersToDashboard';
import { TVariableMode } from './types';
import VariableItem from './VariableItem/VariableItem';
@@ -92,8 +93,6 @@ function VariablesSettings({
const { dashboardData, setDashboardData } = useDashboardStore();
const { dashboardVariables } = useDashboardVariables();
- const { notifications } = useNotifications();
-
const [variablesTableData, setVariablesTableData] = useState<any>([]);
const [variblesOrderArr, setVariablesOrderArr] = useState<number[]>([]);
const [existingVariableNamesMap, setExistingVariableNamesMap] = useState<
@@ -201,9 +200,7 @@ function VariablesSettings({
onSuccess: (updatedDashboard) => {
if (updatedDashboard.data) {
setDashboardData(updatedDashboard.data);
- notifications.success({
- message: t('variable_updated_successfully'),
- });
+ toast.success(t('variable_updated_successfully'));
}
},
},
@@ -256,6 +253,11 @@ function VariablesSettings({
};
const handleDeleteConfirm = (): void => {
+ if (!dashboardData || !variableToDelete.current) {
+ setDeleteVariableModal(false);
+ return;
+ }
+
const newVariablesArr = variablesTableData.filter(
(variable: IDashboardVariable) =>
variable.id !== variableToDelete?.current?.id,
@@ -263,7 +265,31 @@ function VariablesSettings({
const updatedVariables = convertVariablesToDbFormat(newVariablesArr);
- updateVariables(updatedVariables);
+ const cleanedDashboard =
+ removeVariableReferencesFromDashboard(
+ dashboardData,
+ variableToDelete.current.name || '',
+ ) || dashboardData;
+
+ updateMutation.mutateAsync(
+ {
+ id: dashboardData.id,
+
+ data: {
+ ...cleanedDashboard.data,
+ variables: updatedVariables,
+ },
+ },
+ {
+ onSuccess: (updatedDashboard) => {
+ if (updatedDashboard.data) {
+ setDashboardData(updatedDashboard.data);
+ toast.success(t('variable_updated_successfully'));
+ }
+ },
+ },
+ );
+
variableToDelete.current = null;
setDeleteVariableModal(false);
};
@@ -476,6 +502,7 @@ function VariablesSettings({
open={deleteVariableModal}
onOk={handleDeleteConfirm}
onCancel={handleDeleteCancel}
+ okButtonProps={{ loading: updateMutation.isLoading }}
>
<Typography.Text>
Are you sure you want to delete variable{' '}