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.

feat(dashboard-v2): link variables to panels and substitute them into panel queries (#11909)

Ashwin Bhatkal3ea62d3d5025
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useResolvedVariables.test.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useResolvedVariables.test.tsx
new file mode 100644
index 0000000000..192fc2c512
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useResolvedVariables.test.tsx
@@ -0,0 +1,67 @@
+import { renderHook } from '@testing-library/react';
+import type {
+ DashboardtypesGettableDashboardV2DTO,
+ DashboardtypesVariableDTO,
+} from 'api/generated/services/sigNoz.schemas';
+
+import { selectResolvedVariables } from '../../store/slices/variableSelectionSlice';
+import { useDashboardStore } from '../../store/useDashboardStore';
+import { useResolvedVariables } from '../useResolvedVariables';
+
+// A text variable is the simplest envelope (no list plugin); the builder's full
+// type/value matrix is covered in buildVariablesPayload.test.ts. The envelope is
+// cast at the boundary — its kind discriminant is the literal 'TextVariable'.
+function textVariable(name: string, value: string): DashboardtypesVariableDTO {
+ return {
+ kind: 'TextVariable',
+ spec: { name, value, display: { name } },
+ } as unknown as DashboardtypesVariableDTO;
+}
+
+function dashboard(
+ id: string,
+ variables: DashboardtypesVariableDTO[],
+): DashboardtypesGettableDashboardV2DTO {
+ return {
+ id,
+ spec: { variables },
+ } as unknown as DashboardtypesGettableDashboardV2DTO;
+}
+
+describe('useResolvedVariables', () => {
+ afterEach(() => {
+ useDashboardStore.setState({ variableValues: {}, resolvedVariables: {} });
+ });
+
+ it('publishes the resolved V5 payload for the dashboard to the store', () => {
+ renderHook(() =>
+ useResolvedVariables(dashboard('d1', [textVariable('env', 'prod')])),
+ );
+
+ expect(
+ selectResolvedVariables('d1')(useDashboardStore.getState()),
+ ).toStrictEqual({ env: { type: 'text', value: 'prod' } });
+ });
+
+ it('reflects the runtime selection over the configured default', () => {
+ useDashboardStore
+ .getState()
+ .setVariableValues('d2', { env: { value: 'staging', allSelected: false } });
+
+ renderHook(() =>
+ useResolvedVariables(dashboard('d2', [textVariable('env', 'prod')])),
+ );
+
+ expect(
+ selectResolvedVariables('d2')(useDashboardStore.getState()),
+ ).toStrictEqual({ env: { type: 'text', value: 'staging' } });
+ });
+
+ it('publishes an empty payload when the dashboard has no variables', () => {
+ renderHook(() => useResolvedVariables(dashboard('d3', [])));
+
+ expect(
+ selectResolvedVariables('d3')(useDashboardStore.getState()),
+ ).toStrictEqual({});
+ });
+});
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery.ts
index e7cc207e2e..b5c8d99369 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery.ts
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery.ts
@@ -17,6 +17,8 @@ import type { PanelPagination, PanelQueryData } from '../queryV5/types';
import { getRawResults } from '../queryV5/v5ResponseData';
import { getBuilderQueries } from '../Panels/utils/getBuilderQueries';
import { PANEL_KIND_TO_PANEL_TYPE } from '../Panels/types/panelKind';
+import { selectResolvedVariables } from '../store/slices/variableSelectionSlice';
+import { useDashboardStore } from '../store/useDashboardStore';
import { resolvePanelTimeWindow } from './resolvePanelTimeWindow';
import { useGetQueryRangeV5 } from './useGetQueryRangeV5';
@@ -65,8 +67,9 @@ export interface UsePanelQueryResult {
/**
* Fetches query-range data for a V2 panel over the pure-V5 contract: builds the request DTO
* from the panel's perses queries (no V1 `Query` intermediary), reads global time from Redux,
- * and posts via `useGetQueryRangeV5`. Variable substitution is deferred until V2 has its own
- * variable plumbing. Renderers consume the raw response through the `queryV5` prep utils.
+ * substitutes the dashboard's resolved variable values (published to the store by
+ * `useResolvedVariables`), and posts via `useGetQueryRangeV5`. Renderers consume the raw
+ * response through the `queryV5` prep utils.
*/
export function usePanelQuery({
panel,
@@ -105,6 +108,11 @@ export function usePanelQuery({
minTime,
} = useSelector<AppState, GlobalReducer>((state) => state.globalTime);
+ // Resolved variable values for this dashboard, published by useResolvedVariables.
+ // Substituted into the request and keyed into the cache so a selection change refetches.
+ const dashboardId = useDashboardStore((s) => s.dashboardId);
+ const variables = useDashboardStore(selectResolvedVariables(dashboardId));
+
// `visualization` exists only on variants that declare it — read via `in` narrowing over the
// generated union (no cast). `fillSpans` (TimeSeries/Bar only) → formatOptions.fillGaps.
const pluginSpec = panel.spec.plugin.spec;
@@ -141,8 +149,19 @@ export function usePanelQuery({
endMs,
fillGaps,
pagination: isPaginated ? { offset, limit: pageSize } : undefined,
+ variables,
}),
- [queries, panelType, startMs, endMs, fillGaps, isPaginated, offset, pageSize],
+ [
+ queries,
+ panelType,
+ startMs,
+ endMs,
+ fillGaps,
+ isPaginated,
+ offset,
+ pageSize,
+ variables,
+ ],
);
const legendMap = useMemo(() => extractLegendMap(queries), [queries]);
@@ -167,6 +186,8 @@ export function usePanelQuery({
// Each page is its own cache entry (0/default for non-paged kinds).
offset,
pageSize,
+ // Variable selection changes the request, so it must re-key the cache (refetch).
+ variables,
],
[
panelId,
@@ -182,6 +203,7 @@ export function usePanelQuery({
queries,
offset,
pageSize,
+ variables,
],
);
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useResolvedVariables.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useResolvedVariables.ts
new file mode 100644
index 0000000000..16d4a3398a
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useResolvedVariables.ts
@@ -0,0 +1,42 @@
+import { useEffect, useMemo } from 'react';
+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
+
+import { dtoToFormModel } from '../DashboardSettings/Variables/variableAdapters';
+import { buildVariablesPayload } from '../queryV5/buildVariablesPayload';
+import { selectVariableValues } from '../store/slices/variableSelectionSlice';
+import { useDashboardStore } from '../store/useDashboardStore';
+
+/**
+ * Resolves the dashboard's variable selection into the V5 query payload and
+ * publishes it to the store, so `usePanelQuery` reads it by dashboardId without
+ * the spec being threaded through the panel tree (the `setEditContext` pattern).
+ *
+ * Definitions come from the spec; values come from the runtime selection (seeded
+ * by the variable bar). Re-publishes whenever either changes, which re-keys the
+ * panel queries and triggers a refetch with the new values.
+ */
+export function useResolvedVariables(
+ dashboard: DashboardtypesGettableDashboardV2DTO,
+): void {
+ const dashboardId = dashboard.id ?? '';
+
+ const definitions = useMemo(
+ () => (dashboard.spec?.variables ?? []).map(dtoToFormModel),
+ [dashboard.spec?.variables],
+ );
+
+ const selection = useDashboardStore(selectVariableValues(dashboardId));
+ const setResolvedVariables = useDashboardStore((s) => s.setResolvedVariables);
+
+ const resolved = useMemo(
+ () => buildVariablesPayload(definitions, selection),
+ [definitions, selection],
+ );
+
+ useEffect(() => {
+ if (!dashboardId) {
+ return;
+ }
+ setResolvedVariables(dashboardId, resolved);
+ }, [dashboardId, resolved, setResolvedVariables]);
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx
index b130555e41..bfdbb97f3e 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx
@@ -7,6 +7,7 @@ import { useAppContext } from 'providers/App/App';
import DashboardPageToolbar from './DashboardPageToolbar';
import PanelsAndSectionsLayout from './PanelsAndSectionsLayout';
+import { useResolvedVariables } from './hooks/useResolvedVariables';
import { useDashboardStore } from './store/useDashboardStore';
import styles from './DashboardContainer.module.scss';
import DashboardPageHeader from './components/DashboardPageHeader/DashboardPageHeader';
@@ -50,6 +51,10 @@ function DashboardContainer({
setEditContext,
]);
+ // Resolve the variable selection into the V5 query payload and publish it to
+ // the store, so each panel's query substitutes the bar's selected values.
+ useResolvedVariables(dashboard);
+
const spec = dashboard.spec;
const image = dashboard.image || Base64Icons[0];
const name = spec.display.name;
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/__tests__/buildVariablesPayload.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/__tests__/buildVariablesPayload.test.ts
new file mode 100644
index 0000000000..5167b238d6
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/__tests__/buildVariablesPayload.test.ts
@@ -0,0 +1,103 @@
+import {
+ emptyVariableFormModel,
+ type VariableFormModel,
+ type VariableType,
+} from '../../DashboardSettings/Variables/variableFormModel';
+import type { VariableSelectionMap } from '../../VariablesBar/selectionTypes';
+import { buildVariablesPayload } from '../buildVariablesPayload';
+
+function variable(
+ name: string,
+ type: VariableType,
+ overrides: Partial<VariableFormModel> = {},
+): VariableFormModel {
+ return { ...emptyVariableFormModel(), name, type, ...overrides };
+}
+
+describe('buildVariablesPayload', () => {
+ it('returns an empty map when there are no definitions', () => {
+ expect(buildVariablesPayload([], {})).toStrictEqual({});
+ });
+
+ it('maps each UI variable type to its V5 wire type', () => {
+ const definitions = [
+ variable('q', 'QUERY'),
+ variable('c', 'CUSTOM'),
+ variable('t', 'TEXT'),
+ variable('d', 'DYNAMIC'),
+ ];
+ const selection: VariableSelectionMap = {
+ q: { value: 'a', allSelected: false },
+ c: { value: 'b', allSelected: false },
+ t: { value: 'c', allSelected: false },
+ d: { value: 'e', allSelected: false },
+ };
+ expect(buildVariablesPayload(definitions, selection)).toStrictEqual({
+ q: { type: 'query', value: 'a' },
+ c: { type: 'custom', value: 'b' },
+ t: { type: 'text', value: 'c' },
+ d: { type: 'dynamic', value: 'e' },
+ });
+ });
+
+ it('passes a multi-select array value through verbatim', () => {
+ const definitions = [variable('svc', 'QUERY', { multiSelect: true })];
+ const selection: VariableSelectionMap = {
+ svc: { value: ['a', 'b'], allSelected: false },
+ };
+ expect(buildVariablesPayload(definitions, selection)).toStrictEqual({
+ svc: { type: 'query', value: ['a', 'b'] },
+ });
+ });
+
+ it('collapses a multi-select dynamic ALL selection to the __all__ sentinel', () => {
+ const definitions = [variable('pod', 'DYNAMIC', { multiSelect: true })];
+ const selection: VariableSelectionMap = {
+ pod: { value: null, allSelected: true },
+ };
+ expect(buildVariablesPayload(definitions, selection)).toStrictEqual({
+ pod: { type: 'dynamic', value: '__all__' },
+ });
+ });
+
+ it('does NOT collapse a query ALL selection — it sends the full value array', () => {
+ const definitions = [variable('svc', 'QUERY', { multiSelect: true })];
+ const selection: VariableSelectionMap = {
+ svc: { value: ['a', 'b'], allSelected: true },
+ };
+ expect(buildVariablesPayload(definitions, selection)).toStrictEqual({
+ svc: { type: 'query', value: ['a', 'b'] },
+ });
+ });
+
+ it('falls back to a text variable configured value when unselected', () => {
+ const definitions = [variable('env', 'TEXT', { textValue: 'prod' })];
+ expect(buildVariablesPayload(definitions, {})).toStrictEqual({
+ env: { type: 'text', value: 'prod' },
+ });
+ });
+
+ it('falls back to a list variable configured default when unselected', () => {
+ const definitions = [
+ variable('region', 'QUERY', {
+ defaultValue: { value: 'us-east' },
+ } as unknown as Partial<VariableFormModel>),
+ ];
+ expect(buildVariablesPayload(definitions, {})).toStrictEqual({
+ region: { type: 'query', value: 'us-east' },
+ });
+ });
+
+ it('omits a variable with no selection and no default', () => {
+ const definitions = [variable('q', 'QUERY')];
+ expect(buildVariablesPayload(definitions, {})).toStrictEqual({});
+ });
+
+ it('omits an unnamed variable', () => {
+ const definitions = [variable('', 'QUERY')];
+ const selection: VariableSelectionMap = {
+ '': { value: 'x', allSelected: false },
+ };
+ expect(buildVariablesPayload(definitions, selection)).toStrictEqual({});
+ });
+});
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/buildQueryRangeRequest.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/buildQueryRangeRequest.ts
index 20478d9efa..7c2b49e821 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/buildQueryRangeRequest.ts
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/buildQueryRangeRequest.ts
@@ -6,6 +6,7 @@ import type {
Querybuildertypesv5PromQueryDTO,
Querybuildertypesv5QueryEnvelopeDTO,
Querybuildertypesv5QueryRangeRequestDTO,
+ Querybuildertypesv5QueryRangeRequestDTOVariables,
} from 'api/generated/services/sigNoz.schemas';
import {
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
@@ -202,11 +203,13 @@ export interface BuildQueryRangeRequestArgs {
fillGaps?: boolean;
/** Server-side paging for raw/list panels, written onto the builder queries' `offset`/`limit`. */
pagination?: { offset: number; limit: number };
+ /** Runtime variable values (name → {type,value}) substituted server-side; built by `buildVariablesPayload`. */
+ variables?: Querybuildertypesv5QueryRangeRequestDTOVariables;
}
/**
* Builds the V5 query-range request DTO directly from the panel's perses queries (no V1 `Query`
- * intermediary). Variables are absent (`variables: {}`) until V2 grows its own variable plumbing.
+ * intermediary). `variables` carries the runtime selection (empty when the dashboard has none).
*/
export function buildQueryRangeRequest({
queries,
@@ -215,6 +218,7 @@ export function buildQueryRangeRequest({
endMs,
fillGaps = false,
pagination,
+ variables = {},
}: BuildQueryRangeRequestArgs): Querybuildertypesv5QueryRangeRequestDTO {
let envelopes = toQueryEnvelopes(queries);
if (panelType === PANEL_TYPES.BAR) {
@@ -234,7 +238,7 @@ export function buildQueryRangeRequest({
formatTableResultForUI: panelType === PANEL_TYPES.TABLE,
fillGaps,
},
- variables: {},
+ variables,
};
}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/buildVariablesPayload.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/buildVariablesPayload.ts
new file mode 100644
index 0000000000..2111b99973
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/buildVariablesPayload.ts
@@ -0,0 +1,105 @@
+import type {
+ Querybuildertypesv5QueryRangeRequestDTOVariables,
+ Querybuildertypesv5VariableItemDTOValue,
+} from 'api/generated/services/sigNoz.schemas';
+import { Querybuildertypesv5VariableTypeDTO } from 'api/generated/services/sigNoz.schemas';
+
+import type {
+ VariableFormModel,
+ VariableType,
+} from '../DashboardSettings/Variables/variableFormModel';
+import type {
+ SelectedVariableValue,
+ VariableSelection,
+ VariableSelectionMap,
+} from '../VariablesBar/selectionTypes';
+
+/**
+ * Backend sentinel for "every value selected" on a multi-select dynamic variable.
+ * V1 parity (`getDashboardVariables`): only dynamic vars collapse to `__all__`;
+ * query/custom multi-selects send the full value array instead. Lowercase — the
+ * URL/store `__ALL__` sentinel is a separate serialization concern.
+ */
+const ALL_VALUES_SENTINEL = '__all__';
+
+/** UI variable grouping → the V5 wire `variables[].type`. */
+const VARIABLE_TYPE_TO_DTO: Record<
+ VariableType,
+ Querybuildertypesv5VariableTypeDTO
+> = {
+ QUERY: Querybuildertypesv5VariableTypeDTO.query,
+ CUSTOM: Querybuildertypesv5VariableTypeDTO.custom,
+ TEXT: Querybuildertypesv5VariableTypeDTO.text,
+ DYNAMIC: Querybuildertypesv5VariableTypeDTO.dynamic,
+};
+
+/** The variable's configured default, used when nothing is selected yet. */
+function configuredDefault(
+ definition: VariableFormModel,
+): SelectedVariableValue | undefined {
+ if (definition.type === 'TEXT') {
+ return definition.textValue || undefined;
+ }
+ return (
+ definition.defaultValue as { value?: SelectedVariableValue } | undefined
+ )?.value;
+}
+
+/**
+ * Resolves the wire value for one variable: the dynamic "ALL" sentinel, else the
+ * user's selection, else the configured default. Returns `undefined` when there
+ * is nothing meaningful to send (the variable is then omitted from the payload).
+ */
+function resolveValue(
+ definition: VariableFormModel,
+ selection: VariableSelection | undefined,
+): Querybuildertypesv5VariableItemDTOValue | undefined {
+ if (
+ definition.type === 'DYNAMIC' &&
+ definition.multiSelect &&
+ selection?.allSelected
+ ) {
+ return ALL_VALUES_SENTINEL;
+ }
+
+ const selected = selection?.value;
+ const hasSelection =
+ selected !== null &&
+ selected !== undefined &&
+ !(typeof selected === 'string' && selected === '');
+ if (hasSelection) {
+ return selected as Querybuildertypesv5VariableItemDTOValue;
+ }
+
+ const fallback = configuredDefault(definition);
+ return fallback == null
+ ? undefined
+ : (fallback as Querybuildertypesv5VariableItemDTOValue);
+}
+
+/**
+ * Builds the V5 `variables` map from the dashboard's variable definitions and the
+ * runtime selection, so a panel query substitutes the values the user picked in
+ * the variable bar (V1 parity with `getDashboardVariables` + the V5 prep). The
+ * definition list supplies the wire `type` (the selection map carries only values).
+ */
+export function buildVariablesPayload(
+ definitions: VariableFormModel[],
+ selection: VariableSelectionMap,
+): Querybuildertypesv5QueryRangeRequestDTOVariables {
+ const payload: Querybuildertypesv5QueryRangeRequestDTOVariables = {};
+ definitions.forEach((definition) => {
+ if (!definition.name) {
+ return;
+ }
+ const value = resolveValue(definition, selection[definition.name]);
+ if (value === undefined) {
+ return;
+ }
+ payload[definition.name] = {
+ type: VARIABLE_TYPE_TO_DTO[definition.type],
+ value,
+ };
+ });
+ return payload;
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/store/slices/variableSelectionSlice.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/store/slices/variableSelectionSlice.ts
index 7c172a0f74..f6dbb00bc1 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/store/slices/variableSelectionSlice.ts
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/store/slices/variableSelectionSlice.ts
@@ -1,3 +1,4 @@
+import type { Querybuildertypesv5QueryRangeRequestDTOVariables } from 'api/generated/services/sigNoz.schemas';
import type { StateCreator } from 'zustand';
import type {
@@ -12,9 +13,19 @@ import type { DashboardStore } from '../useDashboardStore';
* localStorage (mirrored to the URL by the bar for shareable links); it is
* deliberately NOT part of the dashboard spec, so selecting a value never
* patches the dashboard.
+ *
+ * `resolvedVariables` is the same selection resolved into the V5 query payload
+ * shape (`{ name: { type, value } }`), published by `useResolvedVariables` so
+ * `usePanelQuery` reads it without threading the dashboard spec down the tree
+ * (the edit-context publish pattern). Transient — not persisted (it is derived
+ * from `variableValues` + the spec on every load).
*/
export interface VariableSelectionSlice {
variableValues: Record<string, VariableSelectionMap>;
+ resolvedVariables: Record<
+ string,
+ Querybuildertypesv5QueryRangeRequestDTOVariables
+ >;
setVariableValue: (
dashboardId: string,
name: string,
@@ -22,6 +33,11 @@ export interface VariableSelectionSlice {
) => void;
/** Bulk set (used to seed from URL/localStorage/defaults on load). */
setVariableValues: (dashboardId: string, values: VariableSelectionMap) => void;
+ /** Publish the resolved V5 variables payload for a dashboard. */
+ setResolvedVariables: (
+ dashboardId: string,
+ variables: Querybuildertypesv5QueryRangeRequestDTOVariables,
+ ) => void;
}
export const createVariableSelectionSlice: StateCreator<
@@ -31,6 +47,7 @@ export const createVariableSelectionSlice: StateCreator<
VariableSelectionSlice
> = (set, get) => ({
variableValues: {},
+ resolvedVariables: {},
setVariableValue: (dashboardId, name, selection): void => {
const { variableValues } = get();
set({
@@ -46,6 +63,12 @@ export const createVariableSelectionSlice: StateCreator<
variableValues: { ...variableValues, [dashboardId]: values },
});
},
+ setResolvedVariables: (dashboardId, variables): void => {
+ const { resolvedVariables } = get();
+ set({
+ resolvedVariables: { ...resolvedVariables, [dashboardId]: variables },
+ });
+ },
});
/**
@@ -60,3 +83,13 @@ export const selectVariableValues =
(dashboardId: string) =>
(state: DashboardStore): VariableSelectionMap =>
state.variableValues[dashboardId] ?? EMPTY_SELECTION_MAP;
+
+/** Stable empty payload — same rationale as {@link EMPTY_SELECTION_MAP}. */
+const EMPTY_RESOLVED_VARIABLES: Querybuildertypesv5QueryRangeRequestDTOVariables =
+ {};
+
+/** Selector: the resolved V5 variables payload for a dashboard (empty if none). */
+export const selectResolvedVariables =
+ (dashboardId: string) =>
+ (state: DashboardStore): Querybuildertypesv5QueryRangeRequestDTOVariables =>
+ state.resolvedVariables[dashboardId] ?? EMPTY_RESOLVED_VARIABLES;