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 (#12003)

Ashwin Bhatkalcec72e25fd02
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useIsPanelWaitingOnVariable.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useIsPanelWaitingOnVariable.ts
new file mode 100644
index 0000000000..48652ae7de
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useIsPanelWaitingOnVariable.ts
@@ -0,0 +1,23 @@
+import { isResolved } from '../VariablesBar/selectionUtils';
+import { selectVariableValues } from '../store/slices/variableSelectionSlice';
+import { useDashboardStore } from '../store/useDashboardStore';
+
+/**
+ * True while a panel should stay in its loading state because a variable it
+ * references is still loading/waiting and has no usable value yet — i.e. the
+ * first load. Once the variable has a value, a later change no longer blocks the
+ * panel (it refetches over stale data instead). V1 parity with
+ * `useIsPanelWaitingOnVariable`.
+ */
+export function useIsPanelWaitingOnVariable(names: string[]): boolean {
+ const dashboardId = useDashboardStore((s) => s.dashboardId);
+ const states = useDashboardStore((s) => s.variableFetchStates);
+ const selection = useDashboardStore(selectVariableValues(dashboardId));
+
+ return names.some((name) => {
+ const state = states[name];
+ const inFlight =
+ state === 'loading' || state === 'revalidating' || state === 'waiting';
+ return isResolved(selection[name]) ? false : inFlight;
+ });
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery.ts
index 6522eb652e..ea21554dd2 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery.ts
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery.ts
@@ -15,12 +15,14 @@ import {
} from '../queryV5/buildQueryRangeRequest';
import type { PanelPagination, PanelQueryData } from '../queryV5/types';
import { getRawResults } from '../queryV5/v5ResponseData';
+import { getReferencedVariables } from '../queryV5/getReferencedVariables';
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';
+import { useIsPanelWaitingOnVariable } from './useIsPanelWaitingOnVariable';
// V1 parity: PER_PAGE_OPTIONS + default page size from V1's list views.
const LIST_PAGE_SIZE_OPTIONS = [10, 25, 50, 100, 200];
@@ -111,9 +113,34 @@ export function usePanelQuery({
} = 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.
+ // The full set is substituted into every request, but only the values this panel
+ // *references* key the cache — so a variable change refetches only the panels that
+ // use it (V1 parity). Names come from the fetch context (all variables, even
+ // unresolved ones); null before the variable bar initializes it.
const dashboardId = useDashboardStore((s) => s.dashboardId);
const variables = useDashboardStore(selectResolvedVariables(dashboardId));
+ const fetchContext = useDashboardStore((s) => s.variableFetchContext);
+
+ const referencedVariableNames = useMemo(() => {
+ const allNames = fetchContext ? Object.keys(fetchContext.variableTypes) : [];
+ return getReferencedVariables(queries, allNames);
+ }, [queries, fetchContext]);
+
+ const scopedVariables = useMemo(() => {
+ const scoped: typeof variables = {};
+ referencedVariableNames.forEach((name) => {
+ if (variables[name] !== undefined) {
+ scoped[name] = variables[name];
+ }
+ });
+ return scoped;
+ }, [variables, referencedVariableNames]);
+
+ // First-load gate: hold the panel in its loading state until every referenced
+ // variable has resolved a value.
+ const isWaitingOnVariable = useIsPanelWaitingOnVariable(
+ referencedVariableNames,
+ );
// `visualization` exists only on variants that declare it — read via `in` narrowing over the
// generated union (no cast). `fillSpans` (TimeSeries/Bar only) → formatOptions.fillGaps.
@@ -188,8 +215,9 @@ 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,
+ // Only the variables this panel references re-key the cache, so an unrelated
+ // variable change doesn't refetch it.
+ scopedVariables,
],
[
panelId,
@@ -205,14 +233,14 @@ export function usePanelQuery({
queries,
offset,
pageSize,
- variables,
+ scopedVariables,
],
);
const response = useGetQueryRangeV5({
requestPayload,
queryKey,
- enabled: enabled && runnable,
+ enabled: enabled && runnable && !isWaitingOnVariable,
// Hold the current page while the next loads (offset re-keys) so the pager doesn't flash.
keepPreviousData: isPaginated,
});
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useSyncVariablesForSuggestions.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useSyncVariablesForSuggestions.ts
new file mode 100644
index 0000000000..257d1950b1
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useSyncVariablesForSuggestions.ts
@@ -0,0 +1,75 @@
+import { useEffect, useMemo } from 'react';
+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
+import { setDashboardVariablesStore } from 'providers/Dashboard/store/dashboardVariables/dashboardVariablesStore';
+import type {
+ IDashboardVariable,
+ TVariableQueryType,
+} from 'types/api/dashboard/getAll';
+
+import { dtoToFormModel } from '../DashboardSettings/Variables/variableAdapters';
+import {
+ DYNAMIC_SIGNAL_ALL,
+ type VariableFormModel,
+ type VariableType,
+} from '../DashboardSettings/Variables/variableFormModel';
+
+const TYPE_TO_V1: Record<VariableType, TVariableQueryType> = {
+ QUERY: 'QUERY',
+ CUSTOM: 'CUSTOM',
+ TEXT: 'TEXTBOX',
+ DYNAMIC: 'DYNAMIC',
+};
+
+/** Minimal V1-shaped variable — only the fields the shared query builder reads. */
+function toV1Variable(model: VariableFormModel): IDashboardVariable {
+ return {
+ id: model.name,
+ name: model.name,
+ description: model.description,
+ type: TYPE_TO_V1[model.type],
+ queryValue: model.queryValue,
+ customValue: model.customValue,
+ textboxValue: model.textValue,
+ sort: 'DISABLED',
+ multiSelect: model.multiSelect,
+ showALLOption: model.showAllOption,
+ dynamicVariablesAttribute: model.dynamicAttribute,
+ dynamicVariablesSource:
+ model.dynamicSignal === DYNAMIC_SIGNAL_ALL
+ ? 'all sources'
+ : model.dynamicSignal,
+ };
+}
+
+/**
+ * Publishes the V2 dashboard's variables into the shared `dashboardVariablesStore`
+ * that the query builder's autocomplete (`QuerySearch`) reads, so `$variable`
+ * suggestions show up in the panel editor and the dashboards-page query builder.
+ * Suggestion-only — the runtime engine lives in the V2 store. Clears on unmount so
+ * the shared store doesn't leak into other pages.
+ */
+export function useSyncVariablesForSuggestions(
+ dashboard: DashboardtypesGettableDashboardV2DTO | undefined,
+): void {
+ const dashboardId = dashboard?.id ?? '';
+ const specVariables = dashboard?.spec?.variables;
+ const variables = useMemo(
+ () => (specVariables ?? []).map(dtoToFormModel),
+ [specVariables],
+ );
+
+ useEffect(() => {
+ if (!dashboardId) {
+ return undefined;
+ }
+ const record: Record<string, IDashboardVariable> = {};
+ variables.forEach((model) => {
+ if (model.name) {
+ record[model.name] = toV1Variable(model);
+ }
+ });
+ setDashboardVariablesStore({ dashboardId, variables: record });
+ return (): void =>
+ setDashboardVariablesStore({ dashboardId: '', variables: {} });
+ }, [dashboardId, variables]);
+}
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx
index b904dbda06..eb9ea85f18 100644
--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx
@@ -8,6 +8,7 @@ import { useAppContext } from 'providers/App/App';
import DashboardPageToolbar from './DashboardPageToolbar';
import PanelsAndSectionsLayout from './PanelsAndSectionsLayout';
import { useResolvedVariables } from './hooks/useResolvedVariables';
+import { useSyncVariablesForSuggestions } from './hooks/useSyncVariablesForSuggestions';
import { useDashboardStore } from './store/useDashboardStore';
import styles from './DashboardContainer.module.scss';
import DashboardPageHeader from './components/DashboardPageHeader/DashboardPageHeader';
@@ -51,6 +52,10 @@ function DashboardContainer({
// the store, so each panel's query substitutes the bar's selected values.
useResolvedVariables(dashboard);
+ // Publish variables to the shared store so the query builder autocomplete
+ // suggests them ($variable) in the panel editor and dashboards-page builder.
+ useSyncVariablesForSuggestions(dashboard);
+
return (
<FullScreen handle={fullScreenHandle}>
<div className={styles.container}>
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/getReferencedVariables.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/getReferencedVariables.ts
new file mode 100644
index 0000000000..2a691cd04a
--- /dev/null
+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/queryV5/getReferencedVariables.ts
@@ -0,0 +1,47 @@
+import type { DashboardtypesQueryDTO } from 'api/generated/services/sigNoz.schemas';
+import { textContainsVariableReference } from 'lib/dashboardVariables/variableReference';
+
+import { toQueryEnvelopes } from './buildQueryRangeRequest';
+
+// Envelope spec fields that can carry a variable reference: a builder query's
+// filter expression, or a PromQL/ClickHouse query string.
+interface ReferenceableSpec {
+ query?: string;
+ filter?: { expression?: string };
+}
+
+/** Every text string in a panel's queries that could reference a variable. */
+function extractQueryTexts(queries: DashboardtypesQueryDTO[]): string[] {
+ const texts: string[] = [];
+ toQueryEnvelopes(queries).forEach((envelope) => {
+ const spec = envelope.spec as ReferenceableSpec | undefined;
+ if (typeof spec?.query === 'string') {
+ texts.push(spec.query);
+ }
+ if (typeof spec?.filter?.expression === 'string') {
+ texts.push(spec.filter.expression);
+ }
+ });
+ return texts;
+}
+
+/**
+ * The subset of `variableNames` a panel's queries reference (`$name`, `{{.name}}`,
+ * `[[name]]`), so a variable change only refetches the panels that actually use it.
+ * Reuses the shared text-based reference detector over the panel's filter/query text.
+ */
+export function getReferencedVariables(
+ queries: DashboardtypesQueryDTO[],
+ variableNames: string[],
+): string[] {
+ if (queries.length === 0 || variableNames.length === 0) {
+ return [];
+ }
+ const texts = extractQueryTexts(queries);
+ if (texts.length === 0) {
+ return [];
+ }
+ return variableNames.filter((name) =>
+ texts.some((text) => textContainsVariableReference(text, name)),
+ );
+}
diff --git a/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx b/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx
index 1d500733c4..57df7c1aec 100644
--- a/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx
+++ b/frontend/src/pages/DashboardPageV2/PanelEditorPage/PanelEditorPage.tsx
@@ -21,6 +21,7 @@ import {
parseNewPanelKind,
parseNewPanelLayoutIndex,
} from '../DashboardContainer/PanelEditor/newPanelRoute';
+import { useSyncVariablesForSuggestions } from '../DashboardContainer/hooks/useSyncVariablesForSuggestions';
import { createDefaultPanel } from '../DashboardContainer/patchOps';
import styles from './PanelEditorPage.module.scss';
@@ -43,6 +44,9 @@ function PanelEditorPage(): JSX.Element {
const { dashboard, isLoading, isError, error } =
useDashboardFetch(dashboardId);
+ // Feed variables to the query builder autocomplete inside the editor.
+ useSyncVariablesForSuggestions(dashboard);
+
// A `panel/new?panelKind=…` route means "create": seed a default panel of that
// kind rather than looking one up. Persisted (with a real id) only on save.
const newKind = parseNewPanelKind(panelId, search);